The basic process of django self-learning (two)

Seven, start the server

After the pre-configuration work is completed, we can officially start our server. This is a lightweight server provided by Django, which is limited to development and debugging. I saw a sentence in the document ("We are experts in web frameworks, But not a web server expert").

  • We can start the server with the command line
python manage.py runserver ip:port  #(ip和端口可以不写,默认为本机以及8000端口)

Eight, Admin site management

Overview : Regarding the release of database content, as well as copying, adding, deleting, modifying, and checking

  1. First we need to configure the admin application, add admin.contrib.admin to INSTALLED_APPS in setting.py
  2. Create an admin user:
  • Execute the python manage.py createsuperusercommand to enter the user name, email address, and password in turn
  • The website for logging in to the management interface is.../admin
  1. Sinicization
  • The site management page of admin is in pure English, if we want to switch to Chinese, we need to do the following configuration:
    modify in setting.pyLANGUAGE_CODE = 'zh-Hans' TIME_ZONE='Asia/shanghai'
  1. Management table
from django.contrib import admin

# Register your models here.
from .models import Grades, Students  # (自行引入)


# 关联创建(当创建班级表时附带要创建两个学生信息)
class StudentsInfo(admin.TabularInline):  # 也可以用admin.StackedInline
    model = Students
    extra = 2


# 注册
class GradesAdmin(admin.ModelAdmin):
    inlines = [StudentsInfo]  # 关联创建时使用
    # 列表页属性
    list_display = ['pk', 'gname', 'gdate', 'ggirlnum', 'gboynum', 'isDelete']  # 设置要显示的字段
    list_filter = ['gname']  # 设置过滤器
    search_fields = ['gname']  # 设置搜索器
    list_per_page = 5  # 设置每页显示的条数

    # 添加、修改页属性
    fields = ['ggirlnum', 'gboynum', 'gname', 'gdate', 'isDelete']  # 修改添加顺序
    '''
    fieldsets = [                                                   # 给添加的属性进行分组
        ("num", {"fields": ['ggirlnum', 'gboynum']}),
        ("base", {"fields": ['gname', 'gdate', 'isDelete']}),
    ]
    '''
    # 执行动作位置
    actions_on_top = False
    actions_on_bottom = True


admin.site.register(Grades, GradesAdmin)


# 用装饰器注册(可以删除最下面的register注册用装饰器)
# @admin.register(Students)
class StudentsAdmin(admin.ModelAdmin):
    # 用于对布尔值进行判断,逻辑分析后输出
    def gender(self):
        if self.sgender:
            return "男"
        else:
            return "女"

    # 对于字段名进行重定义
    gender.short_description = "性别"

    # 列表页属性
    list_display = ['pk', 'sname', 'sage', gender, 'scontend', 'sgrade', 'isDelete']  # 设置要显示的字段
    list_per_page = 2  # 设置每页显示的条数

    # 添加、修改页属性
    fields = []  # 修改添加顺序
    '''
    fieldsets = []
    '''


admin.site.register(Students, StudentsAdmin)

First, we will import the table to be managed, and then create a class to register the registry, we should pay attention to:

 # 列表页属性
    list_display = ['pk', 'gname', 'gdate', 'ggirlnum', 'gboynum', 'isDelete']  # 设置要显示的字段
    list_filter = ['gname']  # 设置过滤器
    search_fields = ['gname']  # 设置搜索器
    list_per_page = 5  # 设置每页显示的条数

    # 添加、修改页属性
    fields = ['ggirlnum', 'gboynum', 'gname', 'gdate', 'isDelete']  # 修改添加顺序
    '''
    fieldsets = [                                                   # 给添加的属性进行分组
        ("num", {"fields": ['ggirlnum', 'gboynum']}),
        ("base", {"fields": ['gname', 'gdate', 'isDelete']}),
    ]
    '''

This part is about the display constraints of the form and the constraints when it is added. The specific functions have been annotated in the code. When restricting the addition of table data, fields and fieldsets can only be restricted by choosing one of the two .

  1. Associated objects
    According to the foreign key relationship, the student table is associated with the class table, so when creating a class, we can create two additional student information to join the class based on this relationship.
# 关联创建(当创建班级表时附带要创建两个学生信息)
class StudentsInfo(admin.TabularInline):  # 也可以用admin.StackedInline
    model = Students   # 对于要关联的表进行标注
    extra = 2          # 对于要额外创建的个数进行限制

Create the associated class first, and add it to the class registration classinlines = [StudentsInfo] # 关联创建时使用

  1. Boolean value judgment When
    we create a table, some fields are often of Boolean value type, so that when displaying, it will display with true and false, but this is not our intention, we only want to use true for boys and false for girls. So we need to filter Boolean values.
def gender(self):
        if self.sgender:
            return "男"
        else:
            return "女"

    # 对于字段名进行重定义
    gender.short_description = "性别"

Write this code into the student table registration, you can convert the Boolean value into the result we want to display, and change the definition name of the field to display.

  1. Execution position
# 执行动作位置
    actions_on_top = False
    actions_on_bottom = True

Define the view

  1. According to our django MTV programming model, we should customize its own view for each page. First, we come to the app’s views to introduce from django.http import HttpResponseand then write the class to define it.
def index (request):
	return HttpResponse("You are so cute!")
  1. After defining the view, we need to configure the URL. First, modify the import in the urls.py file in the project directory from django.conf.urls import include, and add it to the URLPATTERNS array. path("",include('myAPP.urls'))Create a urls.py file in the application directory of the app to complete the following operations:
from django.conf.urls import url
from . import views
urlpatterns=[
	path("",views.index)
]
  1. Finally, we create the template. We create the templates directory under the statistics directory of the application and the main package, and configure the path of the template. Add [os.path.join(BASE_DIR,'templates) to the'DIRS' in the TEMPLATES in settings.py ')]
    After completing the above work, we can perform simple paging interaction. The following is my view, URL definition, and template example:
  • view
from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse


def index(request):
    return HttpResponse("you are so cute!")


# 查看班级表视图
from .models import Grades


def grades(request):
    # 去模板里取数据
    gradesList = Grades.objects.all()
    # 将数据传递给模板,模板在渲染页面,将渲染好的页面返回浏览器
    return render(request, 'myAPP/grades.html', {
    
    "grades": gradesList})


# 查看学生表视图
from .models import Students


def students(request):
    # 去模板里取数据
    studentsList = Students.objects.all()
    # 将数据传递给模板,模板再渲染页面,将渲染好的页面返回浏览器
    return render(request, 'myAPP/students.html', {
    
    "students": studentsList})


def gradesStudents(request,num):
    grade = Grades.objects.get(pk=num)
    studentsList = grade.students_set.all()
    return render(request, 'myAPP/students.html', {
    
    "students": studentsList})

  • URL
from django.conf.urls import url
from django.urls import path
from . import views

urlpatterns = [
    url(r'^$', views.index),
    path('grades', views.grades),
    path('students', views.students),
    path('grades/<int:num>', views.gradesStudents)  # 这里的num要与视图中定义的函数形参名字一致
]

  • template
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生页面展示</title>
</head>
<body>
    <h1>学生页面展示</h1>
    <ul>
        {
    
    % for student in students %}
        <li>{
    
    {
    
     student.sname }}--{
    
    {
    
     student.scontend }}</li>
        {
    
    % endfor %}
    </ul>
</body>
</html>

Guess you like

Origin blog.csdn.net/baldicoot_/article/details/107158570