Django学习笔记2

创建数据库
(11_env) D:\learning_log>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK

  Applying sessions.0001_initial... OK

windows(使用dir) 或者linux(ls) 可以看到当前文件夹下多了一个db.sqlite3

启动服务器,查看系统中的项目
(11_env) D:\learning_log>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
March 29, 2018 - 23:34:01
Django version 1.8.4, using settings 'learning_log.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK. 打开浏览器输入http://localhost:8000/或
http://127.0.0.1:8000/可以看到shell中有如下信息,并且浏览器也会打开默认的项目

Django学习笔记2_第1张图片

下面是2.0.3展示的html页面,我们1.8.4只有一个简陋的DEBUG=True的提示页面

Django学习笔记2_第2张图片

[

创建应用程序 
这里有人可能会对项目和应用程序区别不太懂,一起来看官网手册吧
Projects vs. apps

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
app是一个完成一些功能的web应用,project是一个特定的网站的配置集合与很多个应用程序。所以我们还要创建应用程序

另打开工作终端,激活虚拟环境,执行命令startapp
D:\learning_log>call 11_env/Scripts/activate.bat
(11_env) D:\learning_log>python manage.py startapp learning_logs

目录结构
learning_logs/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py

    views.py

下面开始我们的实战部分 做一个简单的学习笔记应用

每位用户都需要在学习笔记中创建很多主题。用户输入的每个条目都与

特定的主体相关联,这些条目将以文本的方式显示。还要存储每个条目的时间戳,记录

用户创建的时间。


定义模型models.py

from django.db import models

# Create your models here. 定义模型

class Topic(models.Model):
	"""用户学习的主题"""
	text = models.CharField(max_length = 200)
	data_added = models.DataTimeField(auto_now_add = True)

	def __str__(self):
		"""返回模型的字符串表示"""
		return self.text

激活模型打开learning_log/learning_log中的settings.py

下面片段告诉哪些应用程序安装在项目中

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 我的应用程序
    'learning_logs',
]


让Django修改数据库,使其能够存储与模型Topic相关的信息

(11_env) D:\learning_log>python manage.py makemigrations learning_logs
Migrations for 'learning_logs':
  learning_logs\migrations\0001_initial.py
    - Create model Topic

Django创建了一个迁徙文件0001_initial.py 这个文件在数据库中为模型Topic创建了一张表

应用这种迁徙,让Django替我们修改数据库

(11_env) D:\learning_log>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, learning_logs, sessions
Running migrations:
  Applying learning_logs.0001_initial... OK

Django管理网站
创建超级用户
(11_env) D:\learning_log>python manage.py createsuperuser
Username (leave blank to use 'clarence'): Clarence
Email address: 
Password:
Password (again):
Superuser created successfully.


向管理网站注册模型
Django自动在管理网站中添加了一些模型,如User和Group,但对于我们常见的模型,必须进行手工注册

在我们创建应用程序learning_logs中models.py所在的目录有一个admin.py文件,我们在这里注册模型

from django.contrib import admin

# Register your models here.
# 向管理网站注册模型Topic
from learning_logs.models import Topic 

admin.site.register(Topic)

访问localhost:8000/admin/

Django学习笔记2_第3张图片

Django学习笔记2_第4张图片

添加了一条主题

Django学习笔记2_第5张图片



定义模型Entry,每个条目都与特定的主题相关联,多对一的关系,即多个条目可关联到同一个主题

Entry继承了Django基类的Model.第一个属性topic是一个ForeignKey实例。

    foreign key:一个表中的foreign key指向另一个表中的primary key,一张表中可以有多个外键

from django.db import models

# Create your models here. 定义模型

class Topic(models.Model):
	"""用户学习的主题"""
	text = models.CharField(max_length = 200)
	data_added = models.DateTimeField(auto_now_add = True)

	def __str__(self):
		"""返回模型的字符串表示"""
		return self.text
		
class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name_plural = 'entries'
 
    def __str__(self):
        """Return a string representation of the model."""
        return self.text[:50] + "..."
迁移数据库

(11_env) D:\learning_log>python manage.py makemigrations learning_logs
Migrations for 'learning_logs':
  learning_logs\migrations\0002_entry.py
    - Create model Entry
(11_env) D:\learning_log>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, learning_logs, sessions
Running migrations:

  Applying learning_logs.0002_entry... OK


向管理网站注册Entry 修改admin.py

from django.contrib import admin

# Register your models here.
# 向管理网站注册模型Topic
from learning_logs.models import Topic, Entry

admin.site.register(Topic)
admin.site.register(Entry)

打开管理网站 

Django学习笔记2_第6张图片

Django学习笔记2_第7张图片



你可能感兴趣的:(Django入门学习)