7 月 152021
 

INSTALLED_APPS 默认包括了以下 Django 的自带应用:

django.contrib.admin -- 管理员站点, 你很快就会使用它。
django.contrib.auth -- 认证授权系统。
django.contrib.contenttypes -- 内容类型框架。
django.contrib.sessions -- 会话框架。
django.contrib.messages -- 消息框架。
django.contrib.staticfiles -- 管理静态文件的框架。

默认开启的某些应用需要至少一个数据表,所以,在使用他们之前需要在数据库中创建一些表。migrate 命令检查 INSTALLED_APPS 设置,为其中的每个应用创建需要的数据表。

$ python manage.py migrate

迁移模型

通过运行 makemigrations 命令,Django 会检测你对模型文件的修改(在这种情况下,你已经取得了新的),并且把修改的部分储存为一次 迁移。
迁移是 Django 对于模型定义(也就是你的数据库结构)的变化的储存形式。

(venv) harveymei@MacBookAir mysite % python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Question
- Create model Choice
(venv) harveymei@MacBookAir mysite %

查看迁移命令将会执行的SQL语句

(venv) harveymei@MacBookAir mysite % python manage.py sqlmigrate polls 0001
BEGIN;
--
-- Create model Question
--
CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Create model Choice
--
CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" bigint NOT NULL REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
COMMIT;
(venv) harveymei@MacBookAir mysite %

自动执行数据库迁移并同步管理你的数据库结构的命令 – 这个命令是 migrate

$ python manage.py migrate

(venv) harveymei@MacBookAir mysite % python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, 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 admin.0003_logentry_add_action_flag_choices... 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 auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying polls.0001_initial... OK
Applying sessions.0001_initial... OK
(venv) harveymei@MacBookAir mysite %

migrate 命令选中所有还没有执行过的迁移(Django 通过在数据库中创建一个特殊的表 django_migrations 来跟踪执行过哪些迁移)并应用在数据库上 – 也就是将你对模型的更改同步到数据库结构上。

迁移是非常强大的功能,它能让你在开发过程中持续的改变数据库结构而不需要重新删除和创建表 – 它专注于使数据库平滑升级而不会丢失数据。

改变模型需要这三步:

编辑 models.py 文件,改变模型。
运行 python manage.py makemigrations 为模型的改变生成迁移文件。
运行 python manage.py migrate 来应用数据库迁移。
7 月 152021
 

创建项目

$ django-admin startproject mysite

项目目录及文件说明

最外层的 mysite/ 根目录只是你项目的容器, 根目录名称对 Django 没有影响,你可以将它重命名为任何你喜欢的名称。
manage.py: 一个让你用各种方式管理 Django 项目的命令行工具。
里面一层的 mysite/ 目录包含你的项目,它是一个纯 Python 包。它的名字就是当你引用它内部任何东西时需要用到的 Python 包名。 (比如 mysite.urls).
mysite/__init__.py:一个空文件,告诉 Python 这个目录应该被认为是一个 Python 包。
mysite/settings.py:Django 项目的配置文件。
mysite/urls.py:Django 项目的 URL 声明,就像你网站的“目录”。
mysite/asgi.py:作为你的项目的运行在 ASGI 兼容的 Web 服务器上的入口。
mysite/wsgi.py:作为你的项目的运行在 WSGI 兼容的Web服务器上的入口。

启动用于开发的简易服务器

$ python manage.py runserver

更换端口

$ python manage.py runserver 8080
$ python manage.py runserver 0:8000

创建应用

$ python manage.py startapp polls

函数 include() 允许引用其它 URLconfs。每当 Django 遇到 include() 时,它会截断与此项匹配的 URL 的部分,并将剩余的字符串发送到 URLconf 以供进一步处理。
当包括其它 URL 模式时你应该总是使用 include() , admin.site.urls 是唯一例外。

函数 path() 具有四个参数,两个必须参数:route 和 view,两个可选参数:kwargs 和 name。现在,是时候来研究这些参数的含义了。

path() 参数: route
route 是一个匹配 URL 的准则(类似正则表达式)。当 Django 响应一个请求时,它会从 urlpatterns 的第一项开始,按顺序依次匹配列表中的项,直到找到匹配的项。

这些准则不会匹配 GET 和 POST 参数或域名。例如,URLconf 在处理请求 https://www.example.com/myapp/ 时,它会尝试匹配 myapp/ 。处理请求 https://www.example.com/myapp/?page=3 时,也只会尝试匹配 myapp/。

path() 参数: view
当 Django 找到了一个匹配的准则,就会调用这个特定的视图函数,并传入一个 HttpRequest 对象作为第一个参数,被“捕获”的参数以关键字参数的形式传入。稍后,我们会给出一个例子。

path() 参数: kwargs
任意个关键字参数可以作为一个字典传递给目标视图函数。本教程中不会使用这一特性。

path() 参数: name
为你的 URL 取名能使你在 Django 的任意地方唯一地引用它,尤其是在模板中。这个有用的特性允许你只改一个文件就能全局地修改某个 URL 模式。
10 月 212020
 
PS D:\Python\mysite> django-admin.exe

Type 'django-admin help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
runserver
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). 
PS D:\Python\mysite>
10 月 192020
 

安装Django(提示已安装)

PS D:\Python> python.exe -m pip install Django
Requirement already satisfied: Django in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (3.1.2)
Requirement already satisfied: asgiref~=3.2.10 in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (3.2.10)
Requirement already satisfied: sqlparse>=0.2.2 in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (0.4.1)
Requirement already satisfied: pytz in c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages (from Django) (2020.1)
PS D:\Python> 

查看Django版本信息

import django
print(django.get_version())

PS D:\Python> & C:/Users/harveymei/AppData/Local/Programs/Python/Python39/python.exe d:/Python/hello.py
3.1.2
PS D:\Python>

命令行

PS D:\Python> python.exe -m django --version
3.1.2
PS D:\Python>

PS D:\Python> python.exe -m pip show django
Name: Django
Version: 3.1.2
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD-3-Clause
Location: c:\users\harveymei\appdata\local\programs\python\python39\lib\site-packages
Requires: sqlparse, pytz, asgiref
Required-by:
PS D:\Python>

创建项目

PS D:\Python> django-admin.exe startproject mysite
PS D:\Python> 

目录结构

mysite/             #根目录可以任意修改
    manage.py       #管理Django项目的命令行工具
    mysite/         #包名
        __init__.py #空文件,告诉Python将该目录当作python包
        settings.py #项目配置文件
        urls.py     #项目URL声明
        asgi.py     #项目运行在ASGI兼容服务器的入口
        wsgi.py     #项目运行在WSGI兼容服务器的入口

启动Django内置轻量级Web服务器

PS D:\Python> cd .\mysite\
PS D:\Python\mysite> python.exe .\manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 19, 2020 - 11:43:15
Django version 3.1.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/ 
Quit the server with CTRL-BREAK.

指定监听端口

PS D:\Python\mysite> python.exe .\manage.py runserver 8080
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 19, 2020 - 11:53:53
Django version 3.1.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
[19/Oct/2020 11:54:05] "GET / HTTP/1.1" 200 16351
[19/Oct/2020 11:54:06] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184
[19/Oct/2020 11:54:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692    
Not Found: /favicon.ico
[19/Oct/2020 11:54:06] "GET /favicon.ico HTTP/1.1" 404 1972

指定监听端口和IP(0是0.0.0.0的简写)

PS D:\Python\mysite> python.exe .\manage.py runserver 0:8080