One, install Django and initialize
- Create a project in the appropriate directory
- Open the cmd terminal and enter the directory created in the previous step
- input the command
django -admin startproject project
- Directory level description:
- manage.py, a command line tool that can interact with Django projects in a variety of ways
- project\init.py, an empty file, which tells Python that this directory should be treated as a Python package
- project\settings.py, the configuration file of the project
- project\urls.py, the URL statement of the project
- project\wsgi.py, the entry to the web server compatible with WSGI
Second, configure the database
- Database configuration: Django uses SQLite database by default,
- Add the following content to the init.py file under the project folder
import pymysql
pymysql.install_as_MySQLdb()
- View the configuration items in the settings file, and modify the database as follows
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'student', # 数据库名称
'HOST':'192.168.159.6', # IP地址
'PORT':'3306', # 端口号
'USER':'root', # 用户名
'PASSWORD':'123456', # 密码
}
}
Three, create an application
- Application introduction: Multiple applications can be created in a project, and each application only handles one type of business logic
- Create an application:
- Open the cmd window and enter the project directory
- Execute the following command
python manage.py startapp MyApp
- MyApp catalog description:
- admin.py, site configuration
- models.py, models
- views.py, views
- Activate the application:
- In the project directory, in the settings.py file, add MyApp to the INSTALLED_APPS option, the effect is as follows
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'MyApp'
]
Four, define the model
- Model introduction: There are several tables in the database, you need to define several models; each attribute in the model corresponds to each field in the model comparison table
- Introduction to the attributes in the model, see
https://blog.csdn.net/zhuan_long/article/details/114022089
- Define the model: define the model in the models.py file, the code is as follows
from django.db import models
class Grade(models.Model):
gradeName = models.CharField(max_length=64)
startTime = models.DateTimeField()
girlNum = models.IntegerField(max_length=64)
boyNum = models.IntegerField(max_length=64)
isDelete = models.BooleanField(default=False)
def __str__(self):
return self.gradeName
class Student(models.Model):
studentName = models.CharField(max_length=64)
studentAge = models.IntegerField(max_length=64)
#grade = models.IntegerField(max_length=64)
# 关联外键
grade = models.ForeignKey("Grade",on_delete=models.DO_NOTHING) # 删除关联数据,什么也不做
isDelete = models.BooleanField(default=False)
# 不需要定义主键,在生成时会自动增加
def __str__(self):
return self.studentName
- The data table generates the migration file: open the cmd window, enter the project directory, and execute the following command
python manage.py makemigrations
Generate a migration file in the migrations directory, and there is no data table in the database at this time.
5. Perform file migration: open the cmd window, enter the project directory, and execute the following command, which is equivalent to executing SQL statements to create a data table
python manage.py migrate
Five, start the server
- Start the server statement: open the cmd window, enter the project directory, and execute the following command
python manage.py runserver ip:port
Six, Admin site management
- Configure Admin application: add "django.contrib.admin" to INSTALLED_APPS in the settings.py file, which has been added by default
- Add an administrator account: open the cmd window, enter the project directory, and execute the following command
python manage.py createsuperuser
- Localization of Admin site: modify the settings.py file
LANGUAGE_CODE = "zh-Hans"
TIME_ZONE = "Asia/Shanghai"
- Modify the MyApp/admin.py file
from django.contrib import admin
# Register your models here.
from .models import Grade,Student
# 以下功能实现创建班级时同步创建2个学生
class StudentsInfo(admin.TabularInline): # admin.StackedInline 也可以,创建时样式不同
model = Student
extra = 2
# 注册
@admin.register(Grade) # 使用装饰器注册,后面不需要额外注册语句
class GradesAdmin(admin.ModelAdmin):
# 以下功能实现创建班级时同步创建2个学生
inlines = [StudentsInfo]
# 列表页属性
list_display = ["gradeName","startTime","girlNum","boyNum","isDelete"] # 显示字段
list_filter = ["startTime"] # 过滤字段
search_fields = ["startTime"] # 搜索字段
list_per_page = 5 # 分页字段
# 添加,修改页属性
# fields = ["girlNum","boyNum","gradeName","startTime","isDelete"] # 可以规定属性的先后顺序
fieldsets = [
("num",{"fields":["girlNum","boyNum"]}),
("base",{"fields":["gradeName","startTime","isDelete"]})
] # 分组并规定先后顺序
# fields 与 fieldsets 不能同时生效
@admin.register(Student) # 使用装饰器注册,后面不需要额外注册语句
class StudentAdmin(admin.ModelAdmin):
# 数据库中isDelete是布尔值,使用此方法可以将符号转换为中文
def IsDelete(self):
if self.isDelete == True:
return "已删除"
else:
return "未删除"
def StudentGender(self):
if self.studentGender == True:
return "男"
else:
return "女"
# 设置页面列的名称
StudentGender.short_description = "性别"
IsDelete.short_description = "是否删除"
# 执行动作的位置
actions_on_top = False
actions_on_bottom = True
# 列表页属性
list_display = ["studentName", StudentGender,"studentAge", IsDelete,"grade"] # 显示字段
list_filter = ["studentName"] # 过滤字段
search_fields = ["studentName"] # 搜索字段
list_per_page = 5 # 分页字段
fields = ["studentName","studentGender","studentAge","isDelete","grade"] # 可以规定属性的先后顺序
#admin.site.register(Grade,GradesAdmin)
#admin.site.register(Student,StudentAdmin)
Seven, the introduction of the view
-
Concept: In Django, a view is a response to a web request, and a view is a Python function defined in \Django\MyDjango\project\MyApp\urls.py
-
Configure URL \Django\MyDjango\project\MyApp\urls.py add the following
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^(\d+)/(\d+)$',views.detail)
]
\Django\MyDjango\project\project\urls.py add the following
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^',include('MyApp.urls')),
]
- Define the return result: \Django\MyDjango\project\MyApp\views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Sunck is a good man")
def detail(request,num1,num2):
return HttpResponse("detail - %s - %s"%(num1,num2))
- Test verification: restart the service, use the browser to visit 127.0.0.1:8000/
Eight, template
- Add a template directory: modify the settings.py file in the directory to modify part of the TEMPLATES content:
\Django\MyDjango\project\project\settings.py
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',
],
},
},
]
- Create html file in the directory
- \Django\MyDjango\project\templates\MyApp\grades.html
grades.html add content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>班级信息</title>
</head>
<body>
<h1>班级信息列表</h1>
<ul>
<li>
<a href="#">班级名称</a>
</li>
<!--[python04,python05,python06]-->
{%for gradeHtml in gradesHtml%}
<li>
<a href="{
{gradeHtml.id}}">{
{gradeHtml.gradeName}}</a>
</li>
{%endfor%}
</ul>
</body>
</html>
- \Django\MyDjango\project\templates\MyApp\students.html
students.html add content
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>学生信息</title>
</head>
<body>
<h1>学生信息列表</h1>
<ul>
<li>
<a href="#">学生姓名--学生年龄--学生班级</a>
</li>
<!--[python04,python05,python06]-->
{%for studentHtml in studentsHtml%}
<li>
<a href="#">{
{studentHtml.studentName}}--{
{studentHtml.studentAge}}--{
{studentHtml.grade_id}}</a>
</li>
{%endfor%}
</ul>
</body>
</h tml>
- Add routing information
\Django\MyDjango\project\MyApp\urls.py to the project's urls.py file
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^(\d+)/(\d+)$',views.detail),
url(r"^grades/$",views.Grades),
url(r"^students/$",views.Students)
]
- Specify the page path in the view file: \Django\MyDjango\project\MyApp\views.py add
from .models import Grade
def Grades(requset):
# 模板中取数据
GradesList = Grade.objects.all()
# 将数据传递给模板
return render(requset,'MyApp/grades.html',{"gradesHtml":GradesList})
from .models import Student
def Students(request):
StudentList = Student.objects.all()
return render(request,"MyApp/students.html",{"studentsHtml":StudentList})
-
Start the service, revisit 127.0.0.1:8000/grades, 127.0.0.1:8000/students to see the page content
-
The class is associated with the student
\Django\MyDjango\project\MyApp\views.py Add the following content
def GradesId(request,Num):
grade = Grade.objects.get(pk = Num)
StudentList = grade.student_set.all()
return render(request,"MyApp/students.html",{"studentsHtml":StudentList})
Add the following content to the project URL file \Django\MyDjango\project\MyApp\urls.py
url(r"^grades/(\d+)$",views.GradesId)
- Restart the service, you can click the class link to jump to the student list of this class
Nine, the database table changes
- If the database, table structure has changed, you need to do the following processing
- Modify database information in settings.py
- Delete the migration file in the corresponding project
- Create a project database in the database
- Generate migration file
- Perform migration
- Migration file location, as shown in the figure below