Secure Development3 min read
Django Notes: Creating a Project
Create a project and add an app module. For example, if your project has a login feature, you can name the module login. Generate and configure the app using commands, start the service, configure routes in urls.py, use static files, and add the required settings at the bottom of the root settings.py file…
Read in Chinese→Creating a Project
django-admin startproject Your_Project_Name
Your_Project_Name/ # 你存放项目的文件夹
manage.py # 命令行工具,可以用来启动Django,等等做很多事
Your_Project_Name/ # 目录是真正的项目文件包裹目录,它的名字是你引用内部文件的包名
__init__.py # 定义包的空文件
settings.py # 项目的主配置文件
urls.py # 路由管理,相当于Flask中自己写的app.route('/'),不过这里统一管理,很方便
wsgi.py # 基于WSGI的web服务器进入点,提供底层的网络通信功能
Adding an App Module
For example, suppose your project has a login feature. For now, call this module login. You need to generate and configure this login app. First, navigate to the folder where you created the project and run the command:
python3 manage.py startapp login
login/ # 该登陆模块的文件夹
__init__.py # 包空文件
admin.py # 自动生成强大的后台管理文件
apps.py # 具体我不清楚
migrations/ # 这个文件夹用来操作管理数据库的数据,可以做数据库的迁移之类
__init__.py #
models.py # 用来生成数据库的文件,和Flask中的modules.py一毛一样呢
tests.py # 用来做测试代码的文件,啊,真是贴心呢
views.py # 就像Flask中的视图函数,不过这里专门分了一个文件让你写视图函数
Starting the Service
python3 manage.py runserver
# 启动,默认端口8000
python3 manage.py runserver 8080
# 启动,使用8080端口
python3 manage.py runserver 0:8080
并且修改文件settings.py
ALLOWED_HOSTS = ['*',]
# 启动,监听所有人的访问,即允许所有人访问
Routing: urls.py
urls.py
from django.urls import path
# 这个path函数的功能比较重要,最下面会说
from .views import index,error
# 从视图函数文件中导入创建的两个视图函数
urlpatterns = [
path('', index, name='index'),
# 这里第一个是网址路由,第二个是视图函数,第三个是视图函数指定的名称,可以在任何地方使用这个名称调用这个视图函数
# 哇塞,真实贴心实用呢
path('error/', error, name='error')
# 这个的url目录就是error啦
]
Using static files
Then, in settings.py in the root directory,
add the following at the bottom:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.join(BASE_DIR, 'static')),
)
Configuring HTML
{% load static %}
#这句添加在html文件的最上面
# 然后在需要的地方按照这个格式进行调用,如:
<img src="{% static 'image/404.jpg' %}"/>
This is a blockquote z
PATH函数功能
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 模式。