1. Create a project
1.1 Create a Django project based on the terminal
- open terminal
- Enter the file path (enter the directory where you plan to put the project)
E:\learning\python\Django
- Execute the command to create the project
F:\Anaconda3\envs\pythonWeb\Scripts\django-admin.exe (the path where Django-admin.exe is located) startproject project name
If the Scripts in the environment have been added to the environment variable, you can write directly in the terminal:
django-admin startproject project name
eg: Command to create a project named MySite:
F:\Anaconda3\envs\pythonWeb\Scripts\django-admin.exe startproject MySite
1.2 Create a Django project based on Pycharm
1. Create a new project, select Django, select the project location and interpreter, and click "Create":
说明:
-
The project created through the command line of the terminal is relatively standard
-
Projects created through pycharm are added by default on the basis of the standard:
-
Created a templates directory [delete]
-
Pycaharm adds the part shown on the right to the TEMPLATES configuration item in setting.py (Pycharm adds this means: to find a template, go to the outer templates directory) [Delete]
-
2. Introduction to the default project structure
MySite
├─MySite
│ └─asgi.py 【异步式的接收网络请求】【默认不动】
│ └─wsgi.py【同步式的接收网络请求】【默认不动】
│ └─settings.py 【项目的配置文件:链接数据库,注册APP】【经常修改的文件】
│ └─urls.py 【URL和函数的对应关系】【经常修改的文件】
│ └─__init__.py
└─manage.py 【项目的管理:启动项目、创建app、数据管理】【默认不动,经常使用】
注意:
Use the tree command to display incomplete reasons:tree /f
3.APP
total project
- app, user management [independent table structure, function, HTML master, CSS]
- app, order management [independent table structure, function, HTML master, CSS]
- app, background management [independent table structure, function, HTML master, CSS]
- app, API 【Independent table structure, function, HTML master, CSS】
注意:
When we first started, the project was simple, the development was simple, and we didn’t need many apps. Generally, we only need to create one app.
3.1 Creation of APP
Open the Command Prompt terminal and enter in the terminal:
python manage.py startup app app名
E:.
│ manage.py
│
├─app01
│ │ admin.py 【默认不用动,Django默认提供了admin后台管理】
│ │ apps.py 【默认不用动,app的启动类】
│ │ models.py 【重要,对数据库进行操作的】
│ │ tests.py【默认不动。用来做单元测试的】
│ │ views.py 【重要,定义url对应的视图函数】
│ │ __init__.py
│ │
│ └─migrations 【默认不用动,它是Django的module对数据库字段进行修改的时候,用来做记录的】
│ __init__.py
│
└─MySite
│ asgi.py
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└─__pycache__
settings.cpython-39.pyc
__init__.cpython-39.pyc
4. Quick Start with Django
4.1 Get through the basic data flow
注意:
Before running the Django program, make sure the APP is registered
步骤:
1. Find App01Config in apps.py in app01, and settings.py
write in the INSTALLED_APPS item: 'app01.apps.App01Config'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config'#注册APP01
]
2. urls.py
Write the corresponding relationship between URL and view function in
In MySite, urls.py
first introduce views.py
the view function in app01, and then declare the function and URL correspondingly
- Write the view function in
views.py
:
-
Start the Django project:
-
Start via command line:
python manage.py runserver
-
Pycharm startup: After you can edit the configuration, click the play button to start
-
这样项目基本数据流向就跑通了
4.2 templates template
注意:
- First go to the template in the root directory of the project to find [to be
settings.py
configured in advanceDIRS
] - If you can't find it, then according to the registration order of the app, look for it in the templates directory under each app
4.2.1 Django template syntax
(1) Essence: Write some placeholders in HTML, and replace and process the placeholders by data. The principle of template syntax is shown in the following figure:
注意:
Inside the whole process render:
1. Read HTML files containing template syntax
2. Render internally (template syntax execution and replace data), and finally only get a string containing HTML tags
3. Return the rendered (replaced) string to the user's browser
(2) Template syntax demonstration:
views.py
The corresponding processing function part in:
def usetemp(request):
# 变量
name = '小明'
# 列表
arr = ['小红', '小兰', '小白']
# 字典
dic = {
'name': '小明', 'age': 18, 'address': '北京'}
# 列表套字典
lic = [
{
'name': '小兰', 'age': 18, 'address': '上海'},
{
'name': '小红', 'age': 18, 'address': '天津'},
{
'name': '小白', 'age': 18, 'address': '广东'}
]
return render(request, 'usetemp.html',
{
'name': name,
'friends': arr,
'userinfo': dic,
'friends_info': lic
})
with 模板语法的usetemp.html
code:
<body>
<h1>变量</h1>
<span>{
{ name }}</span>
<h1>数组</h1>
<ul>
<li>{
{ friends.0 }}</li>
<li>{
{ friends.1 }}</li>
<li>{
{ friends.2 }}</li>
</ul>
<ul>
{% for item in friends %}
<li>{
{ item }}</li>
{% endfor %}
</ul>
<h1>字典</h1>
<span>{
{ userinfo.name }}</span>
<span>{
{ userinfo.age }}</span>
<span>{
{ userinfo.address }}</span>
<span>遍历字典索引</span>
<ul>
{% for index in userinfo.keys %}
<li> {
{ index }}</li>
{% endfor %}
</ul>
<span> 遍历字典值</span>
<ul>
{% for value in userinfo.values %}
<li>{
{ value }}</li>
{% endfor %}
</ul>
<span>循环字典的每一项</span>
<ul>
{% for key,value in userinfo.items %}
<li>{
{ key }} = {
{ value }}</li>
{% endfor %}
</ul>
<span>{
{ friends_info.0 }}</span>
<br/>
<span>{
{ friends_info.0.name }}</span>
<h1>条件语句</h1>
{% for item in friends_info %}
{% if item.name == '小芳' %}
<span> 小芳:{
{ item.age }}</span>
{% elif item.name == '小红'%}
<span>小红年龄:{
{ item.age }}</span>
{% else %}
<span> 没有符合条件的用户</span>
{% endif %}
{% endfor %}
</body>
4.3 Static files
Typically during development:
- picture
- CSS
- JS
will be treated as static files.
Static files are in the Django project, steps:
- First create a static folder in the app directory, such as static/img, js, css, plugins
2. The introduction of all static resources in Django:
{% load static %}
The path writing method used:{% static 'img/1.jpeg' %}
5. Request and Response
Common Requests and Responses
request is an object that encapsulates all the data sent by the user
# 1.获取请求方式get/POST
print(request.method)
# 2.获取咋URL上传递的参数值,
print(request.GET['a'])
# 3.post请求会在请求体中传递数据
print(request.POST)
# 4.【响应】HttpResponse("OK"):将字符串的内容返回给请求者
# return HttpResponse('OK')
# 5.【响应】render:读取HTML文件的内容,再进行渲染(替换),生成新的字符串,返回给用户的浏览器
# return render(request, 'req.html')
# 6.【响应】redirect:强制浏览器重定向
return redirect('https://www.baidu.com')
注:
When using the form to submit data, Django's security mechanism will be triggered, just add at the beginning of the form tag:{% csrf_token %}
<form method="POST" action="login">
{
% csrf_token %}
</form>
6. Database operation
MySql+pymysql
import pymysql
#1.连接MysQL
conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',passwd="root123", charset='utf8', db=' unicom ' )
cursor = conn.cursor (cursor=pymysql.cursors.Dictcursor)
#2.发送指令
cursor.execute( "insert into admin(username , password,mobile)values('wupeiqi' , 'qwe123','15155555555')")
conn.commit( )
#3.关闭
cursor.close( )
conn.close()
In Django, MySQL is generally not directly operated through pymysql, which is too cumbersome. Django provides us with an ORM framework
6.1 Install third-party modules for ORM
pip install mysqlclient
6.2 ORM
The role of ORM:
- Create and add, delete, modify and query tables in the database (no need to write SQL statements) [Note: the database cannot be created]
- Manipulate data in the table
Steps for ORM to connect to MySQL:
- Create a database, start MySQL, create a database
CREATE DATABASE CHARACTER SET utf8;
- Configure and modify in settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'XXX', # 数据库名字
'USER': 'root',
'PASSWORD': 'XXX',
'HOST': '127.0.0.1', # 要连接哪台机器上的MySQL
'PORT': '3306' # 端口号
}
}
6.3. Based on Django to operate the table:
6.3.1 Creating tables
1. Edit in models.py under app:
from django.db import models
class UserInfo(models):
name = models.CharField(max_length=32)
password = models.CharField(max_length=64)
age = models.IntegerField()
2. Run the command in the terminal:
python manage.py makemigrations
python manage.py migrate
Note: Before running the command, make sure that the APP has been registered in advance
6.3.2 Modify table
When adding a new column in a table, since there may already be data in the existing column, the new column must specify the data corresponding to the new column:
- Select: 1, then enter the value manually
- Select: 2, then abandon the new column (the default value should be set in the new column)
# 设置默认值
address = models.CharField(default='XXX街道XXX号')
# 允许为空
data = models.IntegerField(null=True, blank=True)
注意:
In the future, if you want to adjust the table structure during development:
- Just operate the class in the models.py file
- Database migration command:
python manage.py makemigrations
python manage.py migrate
6.3.3 Addition, deletion, modification and query of table fields
# 1.新建数据
# models.Department.objects.create(title='活动', segment='销售部')
# models.UserInfo.objects.create(name='xijing', password='123456', age=18)
# 2.删除数据
# 删掉UserInfo里面id=2的记录
# models.UserInfo.objects.filter(id=2).delete()
# 删掉Departemt里面的所有记录
# models.Department.objects.all().delete()
# 3.查数据
#queryset = models.UserInfo.objects.all()
# 得到的是一个列表
# for item in queryset:
# print(item.name,item.age,item.password)
# 获取id=5的数据
# row_data = models.UserInfo.objects.filter(id=5).first()
# print(row_data)
# 4.更新数据
# 将UserInfo表里面所有数据的密码字段全都更新成999
# models.UserInfo.objects.all().update(password='9999')
# 筛选条件
models.UserInfo.objects.filter(id=5).update(password='123456')
7. Case display process
7.1 Display user list
- url
- function
- Get all user information
- HTML rendering
7.2 Add user information
- url
- function
- GET, see the page, enter content
- POST, submit to write to the database
7.3 Delete user
- url
- function
- http://127.0.0.1:8000/info/delet?id=5
- def handlefunc(request):
id = request.GET.get(‘id’)
module.UserInfo.obejects.filter(id=5).delete()
ects.all().update(password=‘9999’)