Django's Form component

1. Introduction to the Form component

1. Several things that the Form component can do

  1. User requests data verification

  2. Automatically generate error messages

  3. Pack the correct information submitted by users

  4. If one of them is wrong, the others are correct, keep the last input

  5. Automatically create input tags and can set styles


2. Django built-in fields are as follows

Field
    required = True, #Whether it is allowed to be empty
    widget = None, #HTML plugin
    label = None, #Used to generate Label labels or display content
    initial = None, #initial value
    help_text = '', #help information (displayed next to the label)
    error_messages = None, #Error message{'required': 'cannot be empty', 'invalid': 'format error'}
    show_hidden_initial = False, #Whether to add a hidden plug-in with default value after the current plug-in (can be used to check whether the two inputs are consistent)
    validators = [], #custom validation rules
    localize = False, #Whether to support localization
    disabled = False, #Whether it can be edited
    label_suffix = None #Label content suffix
    
CharField(Field)
    max_length = None, #maximum length
    min_length = None, #minimum length
    strip = True #whether to remove user input blanks
    
IntegerField(Field)
    max_value = None, #Maximum value
    min_value = None, #minimum
    
DecimalField(IntegerField)
    max_value = None, #Maximum value
    min_value = None, #minimum
    max_digits = None, #total length
    decimal_places = None, #length of decimal places
    
BaseTemporalField(Field)
    input_formats = None # time formatting
    
DateField(BaseTemporalField)      #格式:2015 - 09 - 01

TimeField(BaseTemporalField) # Format: 11: 12

DateTimeField(BaseTemporalField)  #格式:2015 - 09 - 01 11: 12

DurationField(Field) #time interval: % d % H: % M: % S. % f
    ...
    
RegexField(CharField)
    regex, #custom regular expression
    max_length = None, #maximum length
    min_length = None, #minimum length
    error_message = None, #Ignore, use error_messages = {'invalid': '...'} for error messages
    
FileField(Field)
    allow_empty_file = False #Whether empty files are allowed
    
ChoiceField(Field)
    ...
    choices = (), #Options, such as: choices = ((0, 'Shanghai'), (1, 'Beijing'),)
    required = True, #required
    widget = None, #plugin, the default plugin is selected
    label = None, #Label content
    initial = None, #initial value
    help_text = '', #help hint
    
ModelChoiceField(ChoiceField)
    ...                 django.forms.models.ModelChoiceField
    queryset, # query the data in the database
    empty_label = "---------", # default empty display content
    to_field_name = None, # Field corresponding to the value of value in HTML
    limit_choices_to = None # Secondary filtering of queryset in ModelForm
    
ModelMultipleChoiceField(ModelChoiceField)
...                         django.forms.models.ModelMultipleChoiceField

TypedChoiceField(ChoiceField)
    coerce = lambda val: val #Convert the selected value once
    empty_value = '' # default value for empty value
    
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val #Convert once for each selected value
    empty_value = '' #default value of empty value
    
ComboField(Field)
      fields = () #Use multiple validations, as follows: that is to validate the maximum length of 20, and validate the mailbox format fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(), ])
      
SplitDateTimeField(MultiValueField)
    input_date_formats = None, #Format list: ['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
    input_time_formats = None #Format list: ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
    
FilePathField(ChoiceField) #File options, the files in the directory are displayed on the page
    path, #folder path
    match = None, #regular match
    recursive = False, #recursive folders below
    allow_files = True, #Allow files
    allow_folders = False, #Allow folders
    required = True,
    widget = None,
    label = None,
    initial = None,
    help_text = ''
    
GenericIPAddressField
    protocol = 'both', both, ipv4, ipv6 supported IP formats
    unpack_ipv4 = False parses ipv4 address, if it is ::ffff: 192.0.2.1, it can be parsed as 192.0.2.1, PS: protocol must be both to enable


3. Commonly selected plugins

# single radio, the value is a string
user = fields.CharField(
    initial=2,
    widget=widgets.RadioSelect(choices=((1,'Shanghai'),(2,'Beijing'),))
)

# single radio, the value is a string
user = fields.ChoiceField(
    choices=((1, 'Shanghai'), (2, 'Beijing'),),
    initial=2,
    widget=widgets.RadioSelect
)

# Single select, the value is a string
user = fields.CharField(
    initial=2,
    widget=widgets.Select(choices=((1,'Shanghai'),(2,'Beijing'),))
)

# Single select, the value is a string
user = fields.ChoiceField(
    choices=((1, 'Shanghai'), (2, 'Beijing'),),
    initial=2,
    widget=widgets.Select
)

# Multi-select select, the value is a list
user = fields.MultipleChoiceField(
    choices=((1,'Shanghai'),(2,'Beijing'),),
    initial=[1,],
    widget=widgets.SelectMultiple
)

# Single checkbox
user = fields.CharField(
    widget=widgets.CheckboxInput()
)

# Multi-select checkbox, the value is a list
user = fields.MultipleChoiceField(
    initial=[2, ],
    choices=((1, 'Shanghai'), (2, 'Beijing'),),
    widget=widgets.CheckboxSelectMultiple
)


2. Form rendering registration page

views.py file content:

from django.shortcuts import render,HttpResponse
from django import forms
from django.forms import widgets

class UserForm(forms.Form):
    user=forms.CharField(label="username",
                         min_length=5,
                         error_messages={"required":"cannot be empty","min_length":"minimum length cannot be less than 5"},
                         widget=widgets.TextInput(attrs={"class":"form-control"})
                         )
    tel=forms.CharField(label="手机号",max_length=8, widget=widgets.TextInput(attrs={"class":"form-control"}))
    email=forms.EmailField(label="邮箱", widget=widgets.TextInput(attrs={"class":"form-control"}))
def reg(request):
    if request.method=="POST":
        #form=UserForm({"user":"alex999","tel":'123',"email":"111","123":123})
        form=UserForm(request.POST)
        if form.is_valid():
            print("====>",form.cleaned_data) # Fields successfully verified {"user":"alex999","tel":'123'}
            print("====>",form.errors) # Verify failed fields
            return HttpResponse("Added successfully")
        else:
            # print("---->", form.cleaned_data)  #
            # print("---->", type(form.errors))  # <class 'django.forms.utils.ErrorDict'>
            # print("---->", type(form.errors["user"]))  #
            # print("---->", form.errors["user"][0])  #
            return render(request, 'reg.html',{"form":form})
    form=UserForm()
    return render(request,'reg.html',{"form":form})


reg.html file content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <style>
        span{
            color: red!important;
        }
    </style>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
{#####################################Option One:######### ##############################}
<div>
    <div>
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post" novalidate>
                {% csrf_token %}
                {% for filed in form %}
                <div>
                    <label for="">{{ filed.label }}</label>
                    {{ filed }}
                </div>
                {% endfor %}
                <input type="submit">
            </form>
        </div>
    </div>
</div>
{#####################################Option II:######### ##############################}
<div>
    <div>
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post" novalidate>
                {% csrf_token %}
                <div>
                    username:
                    {{ form.user }}
                </div>
                <div>
                    Mail:
                    {{ form.email }}
                </div>
                  <div>
                    Phone number:
                    {{ form.tel }}
                </div>
                <input type="submit">
            </form>
        </div>
    </div>
</div>
{#####################################third solution:######### ##############################}
<div>
    <div>
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post" novalidate>
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit">
            </form>
        </div>
    </div>
</div>



</body>
</html>


3. Examples

views.py file content:

from django.shortcuts import render,redirect
from app01 import models
from django.forms import Form
from django.forms import fields
from django.forms import widgets
class TeacherForm(Form): #Must inherit Form
    username = fields.CharField(
        required=True, #Required field
        error_messages={"required":"Username cannot be empty!!"}, #Display Chinese error message
        widget=widgets.TextInput(attrs={"placeholder":"username","class":"form-control"}) #Automatically generate input box
       )
    password = fields.CharField(required=True, error_messages={'required': 'Password cannot be empty'},
                                widget=widgets.TextInput(attrs={'placeholder': 'password', 'class': 'form-control'})) # cannot be empty
    email = fields.EmailField(
        required=True,
        error_messages={"required":"The mailbox cannot be empty!!","invalid":"Invalid mailbox"},
        widget=widgets.EmailInput(attrs={"placeholder": "mailbox", "class": "form-control"}) # Automatically generate input box
    ) #Cannot be empty and the mailbox format must be consistent
def teacherindex(request):
    teacher_obj = models.UserInfo.objects.all()
    return render(request,"teacherindex.html",{"teacher_obj":teacher_obj})
def add(request):
    if request.method=="GET":
        form = TeacherForm() # just show an input box
        return render(request,"add.html",{"form":form })
    else:
        form = TeacherForm(data=request.POST)
        # print(form)  #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
        if form.is_valid(): # start validation
            # print('executed successfully', form.cleaned_data) # All matches are successful, dictionary
            form.cleaned_data['ut_id'] = 1 #It is necessary to distinguish whether it is a class teacher or a lecturer
            models.UserInfo.objects.all().create(**form.cleaned_data)
            return redirect("/teacherindex/")
        else:
            # print("======?",form.errors,type(form.errors))#Return the result of failure
            # print(form.errors["username"][0]) #Get the result of the return failure and render it to the page
            return render(request,"add.html",{"form":form})


Front-end html page:

{% block right %}
    <h1>Add teacher information</h1>
    <hr>
    <form method="post" novalidate>
        {% csrf_token %}
        <p>姓名:{{ form.username }}</p>{{ form.errors.username.0 }}
        <p>密码:{{ form.password }}</p>{{ form.errors.password.0 }}
        <p>邮箱:{{ form.email }}</p>{{ form.errors.email.0 }}
        <p><input type="submit" value="提交"></p>
    </form>
{% endblock %}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325357820&siteId=291194637