Django-笔记

[toc]

零、资料

视频:

文档:

常用命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
需要pip安装:
Django : web框架
pymysql:操作数据库
cryptography:加密
"""



# 创建工程
django-admin startproject 项目名


# 创建应用
py manage.py startapp 应用名


# 运行
py manage.py runserver


# 创建数据表(通过model的对象,生成数据库)
py manage.py makemigrations
py manage.py migrate


# 创建管理员
python manage.py createsuperuser
# admin后台:root:root

一、安装 Django

前提:安装 Python 3.8以上(本笔记以 3.10为例)

安装 Django:

1
2
# cmd 或 直接Pycharm中安装
python -m pip install Django

配置系统环境变量到 Path:

1
2
3
D:\Python3.10\Scripts

D:\Python3.10\Lib\site-packages\django

查看是否安装成功

1
python -m django --version

创建第一个站点:

  • 创建站点目录:/myDango
  • 进入目录,执行创建项目的命令:django-admin startproject mysite01

生成以下目录结构:

1
2
3
4
5
6
7
8
mysite01/
manage.py
mysite/
__init__.py
settings.py # 项目的配置文件
urls.py # 项目的路由
asgi.py
wsgi.py

运行第一个站点

1
2
3
4
5
# 在站点目录下执行以下命令,即: manage.py所在的目录
# 端口号默认为8000,可省略不写
py manage.py runserver 端口号

# 在浏览器打开:localhost:8000

二、全局配置文件:settings.py

注意:

所有配置名需要大写。

代码中引用配置:from django.conf import settings

1、完整配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-k==8123_25*$by0^%=(!$y)ae&q8lf1l-=mfm97xgufn+i10j3'

# 调试模式:页面可以显示报错消息,项目上线的时候应该改为False
DEBUG = True

# 只允许Http的目标地址为一下ip的请求访问该站点
ALLOWED_HOSTS = ['127.0.0.1']

# 一个项目可以有多个应用,每个应用都需要在此处注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite01.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'mysite01.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

完整配置2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""
Django settings for MyAccountMS project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-xd$$sgl^f0t^dc2+0^0nzdbj&lrl!)m6gj)uxqxbhds-@%aoqw'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'MyAccountMS.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'MyAccountMS.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
'default': {
'ENGINE': 'django.db.backends.mysql', # 默认
'NAME': 'myAccountMS', # 连接的数据库
'HOST': '127.0.0.1', # mysql的ip地址
'PORT': 3306, # mysql的端口
'USER': 'root', # mysql的用户名
'PASSWORD': 'root' # mysql的密码
}
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'templates/static')

STATICFILES_DIRS = [
("css", os.path.join(STATIC_ROOT, 'css')),
("img", os.path.join(STATIC_ROOT, 'images')),
("js", os.path.join(STATIC_ROOT, 'js')),
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

2、开启 debug 模式

1
2
# 调试模式:页面可以显示报错消息,项目上线的时候应该改为False
DEBUG = True

3、按 Host 字段控制访问请求

1
2
# ALLOWED_HOSTS = [*] 允许全部请求
ALLOWED_HOSTS = [‘127.0.0.1’]

4、注册全局路由配置文件

1
ROOT_URLCONF = 'mysite01.urls'

5、注册应用的配置文件

1
2
3
4
5
6
7
8
9
10
# 一个项目可以有多个应用,每个应用都需要在此处注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig', # 注册
]

6、更改站点的语言

1
LANGUAGE_CODE = 'zh-Hans'

7、更改时区

1
2
# 时区改为东八区
TIME_ZONE = 'Asia/Shanghai'

三、URL 与 视图函数

1、Django 处理 URL 请求

小结:

  • 发起 HTTP 请求
  • Django 根据 settings.py中的ROOT_URLCONF配置项,找到 主路由配置文件urls.py
  • 根据 主路由配置文件urls.py中的 urlpatterns数组,匹配 url路径
  • 成功,返回 响应
  • 失败,返回 404

2、视图函数

视图函数的作用:接受请求,返回响应。

编写的位置:<项目同名的文件夹下>/views.py<项目的应用文件夹下>/views.py

mysite01/polls/views.py

1
2
3
4
5
from django.http import HttpResponse

def index(request):
html = "<h1>这是首页</h1>"
return HttpResponse(html)

urls.py

1
2
3
4
5
6
7
8
9
from django.contrib import admin
from django.urls import path,include
# import . from views

urlpatterns = [
# path('polls/', views.index),
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

小结:

  • views.py中,定义视图函数
  • urls.pyurlpatterns配置项中,注册url视图函数映射(需要先导包)

3、路由配置

路由的配置,需要导入 Path 函数(from django.urls import path

练习:

练习-代码:

(1) 创建工程:

1
2
# 进入工作空间,执行以下命令,创建一个名为mysite02的工程
django-admin startproject mysite02

(2) 在项目的同名目录下,创建 views.py

1
2
3
4
5
6
7
8
9
10
11
12
from django.http import HttpResponse

def index(request):
return HttpResponse("你好,这是我的首页")


def page_1(request):
return HttpResponse("这是编号为1的页面")


def page_2(request):
return HttpResponse("这是编号为2的页面")

(3)配置路由:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.contrib import admin
from django.urls import path

# 导入视图函数
from . import views

urlpatterns = [
path('admin/', admin.site.urls),
# 建立url与视图的映射
path('', views.index),
path('page/1/', views.page_1),
path('page/2/', views.page_2),
]

(4)启动网站:

1
2
3
4
# cmd 进入manage.py 所在的目录,执行一下目录启动网站
py manage.py runserver

# 浏览器打开:http://localhost:8000

4、路径转化器

类型转化器的别名,就是要传给视图函数的参数。

转化器类型 说明 实例
str 匹配除“/”外的所有字符串 a/b/<str:username> => a/b/zhangsan
slug 匹配所有的字母、数字、下划线 a/b/<slug:sl> => /a/b/a-a-a_3
int 匹配所有数字 a/b/<int:pageNum> => /a/b/2/
path 匹配所有字符串(包括“/”) a/b/<path:ph> => /a/b/c

对 “路由配置” 章节中的练习的改进:

(1) urls.py

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
# path('page/1/', views.page_1),
# path('page/2/', views.page_2),
# 改进
path('page/<int:pageNum>', views.page_n),

]

(1) views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.http import HttpResponse

def index(request):
return HttpResponse("你好")

def page_1(request):
return HttpResponse("这是编号为1的页面")

def page_2(request):
return HttpResponse("这是编号为2的页面")

# 改进
def page_n(request, pageNum):
return HttpResponse("这是编号为%d的页面" % (pageNum))

5、正则路由转化器

urls.py

1
2
3
4
5
6
7
from django.urls import path
from . import views

urlpatterns = [
path('admin/', admin.site.urls),
re_path("^index/([0-9]{4})/$", views.index),
]

views.py

1
2
3
4
5
from django.shortcuts import HttpResponse

def index(request,year):
print(year) # 一个形参代表路径中一个分组的内容,按顺序匹配
return HttpResponse('菜鸟教程')

四、模板

架构:

模板的使用:

用户访问网站的流程:

1、模板的使用步骤

使用步骤:

  • manage.py所在的目录下,创建templates目录,在该目录下创建HTML页面,通过{{变量名}}占位。
  • settings.py中,修改TEMPLATES配置项的DIRS配置子项。
  • views.py的视图函数中,调用render(request,'模板文件名',字典数据)【需导包】。
  • urls.pyurlpatterns配置项中,添加模板的视图函数。

(1)创建templates目录,创建模板页test_templates.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>这是模板~~~{{username}}</h1>
</body>
</html>

(2)在settings.py中,修改TEMPLATES配置项:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 修改
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

(3)在views.py中,添加视图函数:

1
2
3
4
from django.shortcuts import render

def test_temp(request):
return render(request, 'test_templates.html', {"username": '张三'})

(4)在urls.py中,添加路由(建立 url 与 视图函数 的映射):

1
2
3
4
5
6
from django.urls import path
from . import views

urlpatterns = [
path('testTemplate', views.test_temp),
]

2、模板中的语法

注意:模板中的双大括号无法解析小括号

(1)变量:

(2)if 标签:

1
2
3
4
5
6
7
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}

(3)for 标签

views.py

1
2
3
4
from django.shortcuts import render

def test_for(request):
return render(request, "test_for.html", {"a": 12,"b":[20,30]})

test_for.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<h1>测试 模板中的 for 标签</h1>

{% for i in b%}
{{i}}
{% endfor %}

</body>
</html>

(3)模板过滤器

3、模板的继承

模板继承-小结:

  • 父模板中,定义可以被覆盖重写的区域block
  • 子模版中,继承父模板
  • 子模板,重写父模板

注意:动态的数据是无法继承的!

views.py(视图函数):

1
2
3
4
5
6
7
8
from django.shortcuts import render

def base(request):
return render(request, 'base.html')
def son1(request):
return render(request, 'son1.html')
def son2(request):
return render(request, 'son2.html')

urls.py(路由):

1
2
3
4
5
6
7
8
from django.urls import path
from . import views

urlpatterns = [
path("base", views.base),
path("son1", views.son1),
path("son2", views.son2),
]

base.html(父模板页):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">

<!-- 变化的部分 -->
{% block myTitle %}
<title>父-母版页</title>
{% endblock %}
</head>
<body>
<!-- 不变的部分 -->
<a href="/son1">子页面-1</a>
<br/><br/>
<a href="/son2">子页面-2</a>
<br/><br/>

<!-- 变化的部分 -->
{% block info %}
这是父-模版页
{% endblock %}

</body>
</html>

son1.html(子模板页-1):

1
2
3
4
5
6
7
8
9
10
11
{% extends "base.html" %}


{% block myTitle %}
<title>子-母版页-1</title>
{% endblock %}


{% block info %}
这是子模板页-1
{% endblock %}

son2.html(子模板页-2):

1
2
3
4
5
6
7
8
9
10
11
12
{% extends "base.html" %}


{% block myTitle %}
<title>子-母版页-2</title>
{% endblock %}


{% block info %}
这是子模板页-2
{% endblock %}

五、URL 反向解析

小结:

URL 的反向解析,就是在 urls.pyurlpatterns配置项中,进行path函数的映射时,给映射的url取一个别名,然后在使用url时,直接用别名代替url。

六、静态资源的配置

manage.py所在的目录下,创建templates目录,

templates目录中,创建static目录,

static目录中,创建css目录,js目录,images目录,

settings.py中,配置静态资源的目录:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]



STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'templates/static')

STATICFILES_DIRS = [
("css", os.path.join(STATIC_ROOT, 'css')),
("img", os.path.join(STATIC_ROOT, 'images')),
("js", os.path.join(STATIC_ROOT, 'js')),
]