Django自学笔记-第一章

内容来源: 极客时间

初识Django

MTV架构
设计思想

创建Django项目

Anaconda

安装Anaconda, 略, 直接下载包安装即可

1
2
3
4
5
6
# 创建一个新的conda虚拟环境
conda create -n django python=3.8
# 切换到新的虚拟环境
conda activate django
# 安装Django
conda install django

Pycharm

安装Pycharm, 社区版即可, 安装过程略过, 配置项目解析器情况略过

创建第一个Django项目

1
2
3
4
5
6
7
8
# 使用Django-Admin创建一个项目
django-admin startproject recruitment
# 进入到创建好的项目目录
cd recruitment
# 启动服务
python ./manage.py runserver 0.0.0.0:9999
# 以上指定监听0.0.0.0, 端口9999
# 访问 http://localhost:9999 即可查看到页面
成功展示

尝试进入后台管理页面

尝试访问后台管理页面: http://localhost:9999/admin

后台管理

产生上面错误的原因是我们并未对数据库进行初始化及迁移操作, 应该执行如下操作

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
python recruitment/manage.py makemigrations

>>
No changes detected
>>

python recruitment/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 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 sessions.0001_initial... OK
>>
后台页面

页面可以展示, 尝试使用admin/admin组合登录, 提示用户名密码错误

登录后台

原因是由于未创建超级管理员账号

创建超级管理员账号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
python recruitment/manage.py createsuperuser

>>
Username (leave blank to use 'zrx'): zrx
Email address: zhouruixi@goldwind.com
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
>>

登录成功

使用zrx/123登录成功, 可以看到后台的群组和用户信息

观察当前项目文件情况

项目文件

如上图, 其中各个文件的说明

文件名 用途 说明
asgi.py 异步服务网关接口 Async Service Gateway Interface的缩写. 用于实现异步服务
settings.py 配置文件 整个Django项目的配置文件
urls.py 网页路由信息 存储了所有的路由信息
wsgi.pu 网页服务器网关接口 Web Service Gateway Interface的缩写, 用于实现网页服务
db.sqlite3 项目默认数据库 用于存储项目所有的数据信息
manage.py 项目管理脚本 用于项目服务启动/数据迁移/创建管理员账号等操作