Article From:https://www.cnblogs.com/Kingfan1993/p/9971750.html

Form Introduction

HTMLWhen a form is used to submit data to the back end of a page, some tags are written to get user input and wrapped with form tags.

At the same time, we need to check the user’s input in many scenarios, such as whether the user input, the length and format of the input is correct. If there is an error in the user’s input, it is necessary to display the corresponding error information in the corresponding position on the page.

Django formThe component realizes the functions described above.

To sum up, the main functions of form components are as follows:

Generate HTML tags available for pagesVerification of data submitted by usersRetain the last input

Ordinary Handwriting Registration Function

views.py

# registerDef register (request):Error_msg = ""If request. method == "POST":Username = reqUest. POST. get ("name")PWD = request. POST. get ("pwd")# Verify the registration information uuuuuuuuuuuuIf len (userna)Me) < 6:User Length Less than 6 BitsError_msg= "User name length should not be less than 6 bits"Else:WeiStore username and password in databaseReturn HttpResponse ("successful registration")Return render (request, "register. html", {Error_msg ": error_msg}"

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Registration page & lt; / Title & gt;Lt; / head & gt;< body>Form action = "/ reg /" method = "post" & gt;{% csrf_Token%}< p>User name:Input type = "text" name = "name" & gt;< /p>< p>Password:Input type = "password" name = "pwd" & gt;< /p>< p>Input type= "submit" value= "registration" & gt;< P style= "color: red" & gt; {error_msg}Lt; /p>< /p>Lt; / form & gt;Lt; / body & gt;Lt; / HTML & gt;

Use Form Component to Implement Registration Function

views.py

First, define a RegForm class:

from django import forms

# Write your own class as required by the Django form componentClass RegForm (forms. Form):Name = forms. CharField (label = "user name")PWD= forms.CharField (label= "password")
# Using Form Component to Realize RegistrationDef register2 (request):Form_obj = RegForm ()If request. method == "POST":When # instantiates the form object, the data submitted by the post is passed in directly.Form_obj = RegForm (request. POST)# Call Form_obj SchoolMethod of testing dataIf form_obj.is_valid():Return HttpResponse ("successful registration")Return render (req)Uest,'register2. html', {form_obj': form_obj}

login2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register 2< / title>Lt; / head & gt;< body>< form action="/reg2/" method="post" novalidate aUtocomplete= "off" & gt;{% csrf_token%}< div>< label for="{for"M_obj.name.id_for_label} "& gt; {for m_obj.name.label} & lt; / label>"{form_obj.name} {{form_obj.name.errors.0}}< /div>< div>< label for="{form_obj.pwd.id_for_label} "& gt; {form_obj.pwd.label}} & lt; / label>{form_obj.pWd} {{form_obj.pwd.errors.0}}< /div>< div>< input typeE= "submit" class= "btn btn-success" value= "registration" & gt;< /div>Lt; / form & gt;< /body&gT;Lt; / HTML & gt;

The function of form is also validated by looking at the effect of web pages.
• Front-end page is generated by object of form class – & gt; generating HTML tag function
• When the username and password input is empty or mistyped, the page will prompt – & gt; User Submit Verification Function
• When the user mistyped, the last input was retained in the input box – & gt; the last input was retained.

Common Field and Plug-in

When creating Form class, it mainly involves fields and plug-ins. Fields are used to verify the data requested by users, and plug-ins are used to generate HTML automatically.

initial

Initial value, the initial value in the input box.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="User name, "Initial= "Zhang San" Set default value)PWD = forms. CharField (min_length = 6, label = password)

error_messages

Rewrite the error message.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="User name, "Initial= "Zhang San".Error_messages={"Required": "Can't be empty"."InValid ":" Format error ","Min_length": "User name shortest 8 bits"})PWD = forms. CharField (min_le)Ngth = 6, label = password)

password

class LoginForm(forms.Form):
    ...
    pwd = forms.CharField(
        min_length=6,
        label="Password,Widget = forms. widgets. PasswordInput (attrs ={'class':'c1'}, render_value = True))

radioSelect

Single radio value is a string

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label="User name, "Initial= "Zhang San".Error_messages={"Required": "Can't be empty"."InValid ":" Format error ","Min_length": "User name shortest 8 bits"})PWD = forms. CharField (min_le)Ngth = 6, label = password)Gender = forms. fields. ChoiceFieldChoices=((1,'male'), (2,'female'), (3,"Confidentiality")Label= "gender".Initial=3,Widget = forms. widgets. RadioSelect ())

Radio Select

class LoginForm(forms.Form):
    ...
    hobby = forms.fields.ChoiceField(
        choices=((1, "Basketball, (2,""Football,"(3," "Two-color ball,")Label= "hobbies".Initial=3,Widget = forms. widgets.Select ())

Multiple Select

class LoginForm(forms.Form):
    ...
    hobby = forms.fields.MultipleChoiceField(
        choices=((1, "Basketball, (2,""Football,"(3," "Two-color ball,")Label= "hobbies".Initial= [1,3],Widget = forms. widGets. SelectMultiple ())

radio checkbox

class LoginForm(forms.Form):
    ...
    keep = forms.fields.ChoiceField(
        label="Do you remember the password?Initial= "checked",Widget = forms. widgets. Checkbox Input ())

Multiple Checkbox

class LoginForm(forms.Form):
    ...
    hobby = forms.fields.MultipleChoiceField(
        choices=((1, "Basketball, (2,""Football,"(3," "Two-color ball,")Label= "hobbies".Initial= [1,3],Widget = forms. WidgEts. Checkbox SelectMultiple ())

CHOICE FIELD NOTES”

When choices are used, it is important to note that choices can be configured to be retrieved from the database. However, because the values retrieved from static fields cannot be updated in real time, we need to rewrite the construction method to achieve real-time update of choices.

Method 1:

from django.forms import Form
from django.forms import widgets
from django.forms import fields

 
class MyForm(Form):
 
    user = fields.ChoiceField(
        # choices=((1, 'Shanghai', (2,'Beijing',)Initial=2,Widget = widgets. Select)Def_u init_ (self,*Args,** kwargs:Super (MyForm, self). u init_(* args, ** kwargs)# self. fields ['user'].Choices = ((1,'Shanghai'), (2,'Beijing'),)A kind ofSelf.fields ['user']. choices = models.Classes.oBjects. all (). values_list ('id','caption')

Mode two

from django import forms
from django.forms import fields
from django.forms import models as form_model

 
class FInfo(forms.Form):
    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  # Multiple selection# authors = form_model. ModelChoiceField (queryset = models. NNewType. objects. all ()# radio

Django Form all built-in fields

Field
    required=True,               Is it allowed to be empty?Widget = None, HTML plug-inLabel = None, used to generate Label tags or display contentInitial = None, initial valueHelp_text=', help information (displayed next to the label)Error_messages=None, error message {required':'cannot be empty','invalid':'format error'}Validators=[], custom validation rulesLocalize = False, whether localization is supportedDisad = False, is it editableLabel_suffix=NoNeLabel content suffixCharFieldMax_length = None, maximum lengthMin_length = NoNe, minimum lengthWhether strip = True removes user input blanksIntegerFieldMax_value= None, maximumMin_value = None, minimumFloat Field (Integer Field)...DeCimalFieldMax_value = None, maximumMin_value = None, minimumMax_digits = None, total lengthDecimal_places = None, decimal lengthBaseTemporal Field)Input_formats = None time formattingDateField (Base Temporal Field) format: 2015-09-01TimeField(BaseTemporal Field) format: 11:12Date Time Field (Base Temporal Field) format: 2015-09-01 11:12Duration FieldField) Interval:% d% H:% M:% S.% F...RegexFieldRegex,Self-customized regular expressionsMax_length = None, maximum lengthMin_length = None, minimum lengthError_messaGe = None, ignore, error_messages={invalid':'...'} is used for error informationEmailField (CharField)...FileFieldAllow_empty_file = False whether empty files are allowedImage Field...notesPIL module, PIP3 install PillowWhen using these two dictionaries, we should pay attention to two points:- enctype= "multipart/form-data" in form- Obj = MyForm in the view function (request. POST, request. FILES)URLField...BooleanFielD (Field)...Null Boolean Field...ChoiceField...Choices=(), options, such as: choices = ((0,'Shanghai'), (1,'Beijing'),)Required = True, is it necessary to fill inWidgEt = None, plug-in, default select plug-inLabel = None, Label contentInitial = None,initial valueHelp_text=', Help TipsModel ChoiceField...Django. forms. models. ModelChoiceFieldQueyset, # Query the data in the databaseEmptY_label="-------", # default empty display contentTo_field_name = None, \ HTML value corresponding to the fieldLimit_choiceSecondary filtering of queryset in s_to = None ModelFormModel MultipleChoice Field...Django. forms. models. Model MultipleChoiceFieldTyped ChoiceField (ChoiceF)Ield)Coerce = lambda val: Val converts the selected value onceThe default value of empty_value=''null valueMultipleChoIceField (ChoiceField)...Typed MultipleChoice FieldCoerce = lambda VAL: Val converts each selected value onceThe default value of empty_value=''null valueComboFieldFields= ()Use multiple validations as follows: verify the maximum length of 20, and validate the mailbox formatFields. ComboField (fields=[fi]Elds. CharField (max_length = 20), fields. EmailField (),])MultiValueField (Field)PS: Abstract classes, subclasses can be aggregatedMultiple dictionaries to match a value, in conjunction with MultiWidgetSplit Date Time Field (MultiValue Field)Input_date_formats = None, format columnTable: ['% 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 option, where files are displayed on the page under the directoryPath, folder pathMatch = None, regular matchRecursive = False, recursive folderAllow_files = True,Allow fileAllow_folders = False, allow foldersRequired = True,Widget=None,Label=None,Initial = None,Help_text=''GenericIPAddressFieldProtocol ='both', both, IPv4The IP format supported by IPv6Unpack_ipv4= False resolves IPv4 address, if: ffff: 192.0.2.1, 192.0.2.1, PS: ProtocoL Must be box to enableSlugField numbers, letters, underscores, minus signs (hyphens)...UUIDField (CharField)UUID typeDjango Form built-in fields

Field Check

RegexValidator Verifier

from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator
 
class MyForm(Form):
    user = fields.CharField(
        validators=[RegexValidator(r'^[0-9]+$', 'Please enter the number', Regex Validator (r'^ 159 [0-9]+$','Numbers must begin with 159')],)

Custom Validation Function

import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError
 
 
# Custom Validation RulesDef mobile_validate (value):Mobile_re = re. compile (r'^ (13 [0-9] | 15 [012356789] | 17 [678] | 18 [0-9] | 14 [57] [0-9] {8}$')If not mobile_re. match (value):Raise Validation Error ('Mobile Phone Number Format Error')Class PublishForm (Form):Title = fields. CharField (max_length = 20,Min_length = 5,Error_messages={'required':'Title cannot be empty','min_length':'Title at least 5 characters','max_length':'Title up to 20 characters'},Widget = widgets. TextInput (attrs = {class':"Form-control ",'placeholder':'Title 5-20 characters'})# Use custom validation rulesPhone = fields. CharField (validators = [mobile_validate,],Error_messages={'required':'Cell phones can't be empty'}Widget = widgets. TextInPut (attrs={'class':'form-control')'placeHolder': u'cell phone number'})Email = fields. EmailField (required = False,ErroR_messages={'required': u'mailbox cannot be empty','invalid': u'mailbox format error'},Widget = widgets.TextInput (attrs = {class':'form-control','placeholder': u'mailbox'})

Hook Method

In addition to the above two ways, we can also define hook functions in Form classes to implement custom validation functions.

Apply Bootstrap Style

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
  <title>login</title>
</head>
<body>
<div class="container">
  <div class="row">
    <form action="/login2/" method="post" novalidate class="form-horizontal">
      {% csrf_token %}
      <div class="form-group">
        <label for="{{ form_obj.username.id_for_label }}"
               class="col-md-2 control-label">{{ form_obj.username.label }}</label>
        <div class="col-md-10">
          {{ form_obj.username }}
          <span class="help-block">{{ form_obj.username.errors.0 }}</span>
        </div>
      </div>
      <div class="form-group">
        <label for="{{ form_obj.pwd.id_for_label }}" class="col-md-2 control-label">{{ form_obj.pwd.label }}</label>
        <div class="col-md-10">
          {{ form_obj.pwd }}
          <span class="help-block">{{ form_obj.pwd.errors.0 }}</span>
        </div>
      </div>
      <div class="form-group">
      <label class="col-md-2 control-label">{{ form_obj.gender.label }}</label>
        <div class="col-md-10">
          <div class="radio">
            {% for radio in form_obj.gender %}
              <label for="{{ radio.id_for_label }}">
                {{ radio.tag }}{{ radio.choice_label }}
              </label>
            {% endfor %}
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
          <button type="submit" class="btn btn-default">Registration & lt; / button & gt;< /div>< /div>Lt; / form & gt;< /div>< /div≫Script src="/static/jquery-3.2.1.min.js" & gt; & lt; / script>< script src="/static/bootstr"AP / JS / bootstrap. min. JS "& gt; & lt; / script & gt;"Lt; / body & gt;Lt; / HTML & gt;A simple example of applying Bootstrap style to Django form

Link of this Article: Use of Form Components in Django

Leave a Reply

Your email address will not be published. Required fields are marked *