来源:《Python编程:从入门到实践》
我们要编写一个名为“学习笔记”的Web应用程序,让用户能够记录感兴趣的主题,并在学习每个主题的过程中添加日志条目。“学习笔记”的主页对这个网站进行描述,并邀请用户注册或登录。用户登录后,就可创建新主题、添加新条目以及阅读既有的条目。
python -m venv ll_env
pip install --user virtualenv
注意:如果你使用的是Linux系统,且上面的做法不管用,可使用系统的包管理器来安装virtualenv。例如,要在Ubuntu系统中安装virtualenv,可使用命令sudo apt-get install python-virtualenv
virtualenv ll_env
注意:如果你的系统安装了多个Python版本,需要指定virtualenv使用的版本。例如,命令virtualenv ll_env --python=python3创建一个使用python3的虚拟环境
ll_env\Scripts\activate
pip install Django==1.11
django-admin.py startproject learning_log .
dir
dir learning_log
django-admin.py startproject learning_log .
让Django新建一个名为learning_log的项目。这个命令末尾的句点让新项目使用合适的目录结构,这样开发完成后可轻松地将应用程序部署到服务器注意 : 千万别忘了这个句点,否则部署应用程序时将遭遇一些配置问题。如果忘记了这个句点,就将创建的文件和文件夹删除(ll_env除外),再重新运行这个命令
settings.py
指定Django如何与你的系统交互以及如何管理项目。在开发项目的过程中,将修改其中一些设置,并添加一些设置urls.py
告诉Django应创建哪些网页来响应浏览器请求wsgi.py
帮助Django提供它创建的文件,这个文件名是web server gateway interface(Web服务器网关接口)的首字母缩写(ll_env) F:\python_work\learning_log>python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
utility.execute()
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
django.setup()
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\apps\registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\apps\config.py", line 94, in create
module = import_module(entry)
File "C:\Users\M S I\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "" , line 1006, in _gcd_import
File "" , line 983, in _find_and_load
File "" , line 967, in _find_and_load_unlocked
File "" , line 677, in _load_unlocked
File "" , line 728, in exec_module
File "" , line 219, in _call_with_frames_removed
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module>
from django.contrib.admin.filters import (
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\contrib\admin\options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
File "F:\python_work\learning_log\ll_env\lib\site-packages\django\contrib\admin\widgets.py", line 151
'%s=%s' % (k, v) for k, v in params.items(),
^
SyntaxError: Generator expression must be parenthesized
python manage.py migrate
Django指出它将创建必要的数据库表,用于存储我们将在这个项目(Synchronize unmigrated apps,同步未迁移的应用程序)中使用的信息,再确保数据库结构与当前代码(Apply all migrations,应用所有的迁移)匹配python manage.py runserver
ll_env\Scripts\activate
python manage.py startapp learning_logs
startapp appname
让Django建立创建应用程序所需的基础设施其中重要的文件是models.py、admin.py和views.py
将使用models.py来定义要在应用程序中管理的数据
models.py
from django.db import models
# Create your models here.
from django.db import models
class Topic(models.Model):
"""用户学习的主题"""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""返回模型的字符串表示"""
return self.text
Model——Django中一个定义了模型基本功能的类
属性text是一个CharField——由字符或文本组成的数据
属性date_added是一个DateTimeField——记录日期和时间的数据
实参auto_now_add=True,每当用户创建新主题时,都让Django将这个属性自动设置成当前日期和时间
注意 要获悉可在模型中使用的各种字段,参阅Django Model Field Reference(Django模型字段参考),网址为https://docs.djangoproject.com/en/1.8/ref/models/fields/
settings.py
--snip--
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
--snip--
--snip--
INSTALLED_APPS = [
--snip--
'django.contrib.staticfiles',
# My apps
'learning_logs',
]
--snip--
(ll_env) learning_log>python manage.py makemigrations learning_logs
命令makemigrations让Django确定该如何修改数据库,使其能够存储与我们定义的新模型相关联的数据
(ll_env) learning_log>python manage.py migrate
Applying learning_logs.0001_initial... OK
这里Django确认为learning_logs应用迁移时一切正常(OK)(ll_env) learning_log>python manage.py createsuperuser
Username (leave blank to use 'msi'): ll_admin
Email address:
Password:
Password (again):
Superuser created successfully.
admin.py
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from learning_logs.models import Topic
admin.site.register(Topic)
代码导入要注册的模型Topic,再使用admin.site.register()让Django通过管理网站管理我们的模型
models.py
from django.db import models
class Topic(models.Model):
--snip--
class Entry(models.Model):
"""学到的有关某个主题的具体知识"""
topic = models.ForeignKey(Topic,on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""返回模型的字符串表示"""
return self.text[:50] + "..."
属性topic是一个ForeignKey实例
属性text是一个TextField实例
Entry类中嵌套了Meta类
方法__str__()告诉Django,呈现条目时应显示哪些信息
(ll_env) learning_log>python manage.py makemigrations learning_logs
Migrations for 'learning_logs':
learning_logs\migrations\0002_entry.py
- Create model Entry
(ll_env) 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
admin.py
from django.contrib import admin
from learning_logs.models import Topic, Entry
admin.site.register(Topic)
admin.site.register(Entry)
The opening is the first part of the game, roughly the first ten moves or so. In the opening,
it's a good idea to do three things--bring out your bishops and knights, try to control the center of the board,
and castle your king.
Of course, these are just guidelines. It will be important to learn when to follow these guidelines and
when to disregard these suggestions.
In the opening phase of the game, it's important to bring out your bishops and knights. These pieces
are powerful and maneuverable enough to play a significant role in the beginning moves of a game.
One of the most important concepts in climbing is to keep your weight on your feet as much as possible.
There's a myth that climbers can hang all day on their arms.
这种交互式环境称为Django shell,是测试项目和排除其故障的理想之地
(ll_env) learning_log>python manage.py shell
>>> from learning_logs.models import Topic
>>> Topic.objects.all()
<QuerySet [<Topic: Chess>, <Topic: Rock Climbing>]>
python manage.py shell
启动一个Python解释器,可使用它来探索存储在项目数据库中的数据方法Topic.objects.all()来获取模型Topic的所有实例
它返回的是一个列表,称为查询集
>>> topics = Topic.objects.all()
>>> for topic in topics:
... print(topic.id, topic)
...
1 Chess
2 Rock Climbing
>>> t = Topic.objects.get(id=1)
>>> t.text
'Chess'
>>> t.date_added
datetime.datetime(2019, 9, 3, 3, 17, 23, 266910, tzinfo=<UTC>)
>>> t.entry_set.all()
<QuerySet [<Entry: The opening is the first part of the game, roughly...>, <Entry: In the opening phase of the game, it's important t...>]>
为通过外键关系获取数据,可使用相关模型的小写名称、下划线和单词set
注意: 每次修改模型后,都需要重启shell,这样才能看到修改的效果。要退出shell会话,可按CTRL+D;如果是Windows系统,按CTRL+Z,再看回车键。