Form and model notes

Keywords: Django

Chapter VIII

The django Form function is implemented by the Form class, which is mainly divided into two types
2.django.forms.ModelForm # combines the data form generated by the model

The action in the form tab of the form is used to set the route from which the form data submitted by the user should be received and processed. If it is empty, the submission will be received and processed by the current route. Otherwise, it will jump to the routing address pointed to by the attribute action
The submission request is determined by method

Composition of web form

    {% if v.errors %} <!--v Instantiate a form class-->
            Data error, error message:{{ v.errors }}
    {% else %}
        <form action="" method="post">
        {% csrf_token %}
                <!--Generate a form object into a web form-->
                {{ v.as_table }} as_table <!--Is the form represented purely by template variables-->
            <input type="submit" value="Submit">
    {% endif %}

Define a form class and create a new form file

from django import forms
from .models import *
class VocationForm(forms.Form):
    job = forms.CharField(max_length=20, label='position')
    title = forms.CharField(max_length=20, label='title')
    payment = forms.IntegerField(label='salary') # Can IntegerField set the number to be self increasing and self decreasing
    # Set the value of the drop-down box
    # Query the data of the model PersonInfo
    value = PersonInfo.objects.values('name') # Gets the name in the model field
    # The data is represented in list format, and the list elements are in tuple format
    choices = [(i+1, v['name']) for i, v in enumerate(value)]  # Why only v['name '] is displayed here
    # Set the form field to ChoiceField type and use the generate drop-down box
    person = forms.ChoiceField(choices=choices, label='full name') # choices=choices drop-down box

Comparison of fields and html tags defined in form classes

Field label is converted to label label, and forms.CharField is converted to
input type="text", the name of the job is converted to the parameter name of the control and the max of the form field_ Length becomes the maxlength parameter of the input control

# Form field job of form class VocationForm
job = forms.CharField(max_length=20, label='position')
# html tag
<tr><th><label for="id_job">position:</label></th><td><input type="text" name="job" maxlength="20" required id="id_job"></td></tr>

form source code analysis

The core functions of the form are the definition process of the form, the field type of the form and the parameter type of the form field.

Split line

The source file for the properties and methods of form forms
Main category
class BaseForm: (in class)
Property calls do not add (), function calls add ()

Form field types are similar to model field types
Source location: django/forms/

Source code of model form

Main category
class BaseModelForm: in
The form class ModelForm has no direct data interaction between models. The data interaction between model forms and models is controlled by the function ModelForm_ Implemented by factory, this function binds the custom model form with the model to realize the data interaction between the two.
Function modelform_factory and class ModelForm are defined in the same source file, which defines 9 properties

model, form=ModelForm, fields=None, exclude=None,
                      formfield_callback=None, widgets=None, localized_fields=None,
                      labels=None, help_texts=None, error_messages=None,

Conversion rules between model fields and form fields

Use form in view

Realize the interaction between form data and model

Two summaries to be added

Chapter IX Admin background system

Admin background system enabled by default
Before creating the account password, ensure that the project has performed data migration and created the corresponding data table in the database

Chinese display background

Locate the middleware in the third Middleware in

Two methods of registering models to the background

from django.contrib import admin
from .models import *

# Method 1:
# Register the model directly to the admin background

# Method 2:
# Customize the PersonInfoAdmin class and inherit ModelAdmin
# Register method 1. Bind PersonInfoAdmin and Product with decorator
class PersonInfoAdmin(admin.ModelAdmin): 
    # Set displayed fields
    list_display = ['name', 'age'] # list_display displays personnel information
# Registration method II
#, PersonInfoAdmin)
The background will increase by default xxx(set up verbose_name This is the field, otherwise it is the data table name)

Source code analysis ModelAdmin

Location: django/contrib/admin/
ModelAdmin inherits from BaseModelAdmin, and the metaclass of the parent BaseModelAdmin is MediaDefiningClass. Therefore, the properties and methods of the Admin system are similar to ModelAdmin and BaseModelAdmin
List the properties and methods commonly used in daily development (about the fields and methods displayed in the admin background)

fields Set editable fields on the page of data addition or modification
exclude Set non editable fields on the page of data addition or modification
fieldsets Change the page layout of new or modified pages

# Set the date selector on the data list page
    date_hierarchy = 'recordTime'
# Set searchable fields
    search_fields = ['job', 'title']
 # Set the editing status for the field id and job of the data list page
    list_editable = ['job', 'title']

admin homepage settings

Modify title and header (login interface) = 'MyDjango background management' # this is actually at the top of the url column, like the title of the web page = 'MyDjango' # only this is displayed in the login interface

If you want to change the English of the app application to Chinese, that is, modify the name of the app in the background in the folder where admin is located__ folder

from django.apps import AppConfig
import os
# Modify the name of App displayed in Admin background
# default_ app_ The value of config comes from the class name of
default_app_config = 'index.IndexConfig'

# Get the name of the current App
def get_current_app_name(_file):
    return os.path.split(os.path.dirname(_file))[-1]

# Override class IndexConfig
class IndexConfig(AppConfig):
    name = get_current_app_name(__file__)
    verbose_name = 'index application'

admin background system home page settings

Display name of project application:
Display name of the model:
Verbose in models.py_ Name and verbose_name_plural
Page Title:
Set in admin.py_ Title and attribute
If there are multiple applications in the project, just set under one application (page title)

Realize the secondary development of Admin

Override ModelAdmin
get_ readonly_ The fields function is defined by BaseModelAdmin, which gets readonly_fields to set the model field as a read-only attribute. You can customize the read-only attribute of the model field by overriding this function. For example, you can set the read-only attribute of the model field according to different user roles.

Set field style

The model fields displayed on the data list page are by list_ In display setting, the data of each field comes from the data table, and the data is displayed on the web page in a fixed font format. To perform special processing on the data of some fields, such as setting the font color of the data,.

Function get_queryset()

It is used to query the data information of the model, and then display it on the data list page of Admin. By default, this function performs full table data query. To change the data query method, you can redefine this function, such as performing different data queries according to different user roles.


When adding or modifying data, set the optional value of foreign key

Customize Admin background system

The Admin background system sets a specific routing address for each web page
Redefine the Admin background system, such as the common Xadmin and Django Suit. These plug-ins are redefined based on the Admin background system
The admin background system is created by instantiating the class AdminSite. In other words, redefining the class AdminSite can realize the user-defined development of the admin background system

Registration process of admin background system

When you run django, the Admin background system will run with it. The system registration process of Admin is defined in the source code in django.contrib.admin

To sum up

To realize the custom development of Admin background system, you need to redefine the class AdminSite and change the system registration process of Admin.

Briefly explain how to change the login page of Admin background system

Create the static file in the project directory, add the required javascript files and css files, then place the login page login.html in the templates folder, and finally create the files and in the MyDjango folder
Define the class MyAdminSite in It inherits the parent class admin.AdminSite and overrides the method admin_view() and get_urls() to change the login interface in the background of admin()

Posted by Snooble on Thu, 25 Nov 2021 15:44:22 -0800