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
1.django.forms.Form
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-->
        <p>
            Data error, error message:{{ v.errors }}
        </p>
    {% else %}
        <form action="" method="post">
        {% csrf_token %}
            <table>
                <!--Generate a form object into a web form-->
                {{ v.as_table }} as_table <!--Is the form represented purely by template variables-->
            </table>
            <input type="submit" value="Submit">
        </form>
    {% 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
stay
django/forms/forms.py
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/fields.py

Source code of model form

djano/forms/models.py
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,
                      field_classes=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
'django.contrib.admin',
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 settings.py
'django.middleware.locale.LocaleMiddleware',

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
# admin.site.register(PersonInfo)

# Method 2:
# Customize the PersonInfoAdmin class and inherit ModelAdmin
# Register method 1. Bind PersonInfoAdmin and Product with decorator
@admin.register(PersonInfo)
class PersonInfoAdmin(admin.ModelAdmin): 
    # Set displayed fields
    list_display = ['name', 'age'] # list_display displays personnel information
# Registration method II
# admin.site.register(PersonInfo, 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/options.py
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)
admin.site.site_title = 'MyDjango background management' # this is actually at the top of the url column, like the title of the web page
admin.site.site_header = '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__ init__.py 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 apps.py
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

include:
Display name of project application:
init.py
Display name of the model:
Verbose in models.py_ Name and verbose_name_plural
Page Title:
Set admin.site.site in admin.py_ Title and
admin.site.site_head attribute
If there are multiple applications in the project, just set admin.py 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.

formfield_for_foreignkey

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 apps.py.
apps.py 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 myadmin.py and myapps.py in the MyDjango folder
Define the class MyAdminSite in myadmin.py. 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