Components of the form Django

First, the original registration check

# Rear 
DEF realreg (Request): 
    error = { ' username ' : '' , ' password ' : '' } # define a dictionary storage error 
    IF request.method == ' the POST ' : 
        username = request.POST.get ( ' username ' ) 
        password = request.POST.get ( ' password ' )
     IF len (password) <. 6 : 
        error [ ' password '] = '密码不能小于6位'
    return render(request,'reg.html',{'error':error})

# 前端
<input type='text' name='username'>
<span>{{ error.username }}</span>
<input type='text' name='password'>
<span>{{ error.password }}</span>
  1. Front-end interface is registered, there are a form page Form >>> generate HTML front-end code
  2. form form to be able to submit data to the back-end, back-end do check the validity of data validity checking >>>
  3. Message should check presentation to the page >>> back and check information display

  Inspection data regarding: a front end by JS code check (optional), a rear end through code checking (must), front and rear ends generally do check.

Two, form components

2.1 features

  • Render tag
  • Check data
  • Display information
  • Check information

2.2 form class

Step One: Custom form a class

from django import forms

class MyForm(forms.Form):
name = forms.CharField(max_length=6)
password = forms.CharField(max_length=8,min_length=3)
email = forms.EmailField(required=True)

Step Two: form objects instantiated

= the MyForm form_obj ({ ' name ' : ' moonzier ' , ' password ' : ' 123 ' , ' In Email ' : ' [email protected] ' }) # incoming Dictionary

Step Three: Check the legality of data validation

form_obj.is_valid () # Only when all fields are by check will return True

Step Four: Check validation error message

form_obj.errors # which put a field error and does not pass the checksum of all 
"" " 
{ 
'name': [ 'Ensure® AT MOST has the this value. 6 characters (IT has. 7).'], 
'password': [ '. Ensure® Least AT has the this value. 3 characters (IT has 2)'], 
'In Email': [ 'the Enter A Valid In Email address.'] 
} 
"" "

Step Five: Check the data validation through

form_obj.cleaned_data # compliance with data validation rules will be put in the object

Rule check data form component

  1. Down sequentially from the value of the parity
  2. The check is passed into cleaned_data
  3. Validation failure into errors
  4. All form fields must pass all default values ​​(required = True)
  5. Check data when you can pass (multi-pass data will not do any checking, validation rules will not affect the form)
# Distal canceled check 
<form Action = "" Method = " POST " NOVALIDATE> 
</ form>

2.3 rendering label

  form components only render help you get the label entered by the user, will not help you render the submit button, you need to add manually.

The first: poor scalability

Form_obj.as_p} {} { <-! A <p> tag rendered in -> 
{} {} form_obj.as_ul

The second: one by handwriting

< Form Action = "" > 
< P > {{{{form_obj.name form_obj.name.label}}}} </ P >  <-! If the rear end of the name attribute is not defined, then the field is the first letter capitalized as the label value -> 
< P > {{{{form_obj.password form_obj.password.label}}}} </ P > 
< P > {{{{form_obj.email form_obj.email.label}}}} < / P > 
< INPUT type = "Submit" > 
</ form >

Third: for loop

<form action="">
{% for foo in form_obj %}
<p>{{ foo.label }}{{ foo }}</p>
{% endfor %}
</form>

2.4 Settings tab style

When the form definition of the class, which is provided in the pattern field.

from Django Import Forms
 from `` django.forms`` Import Widgets 
password = forms.CharField (= MAX_LENGTH. 8 , 
                           min_length =. 3 , 
                           error_messages, = {
                                ' MAX_LENGTH ' : ' maximum password 8 ' ,
                                ' required ' : ' password can not be empty ' ,
                                ' min_length ' : ' password least three' 
                           }, 
                           The widget = widgets.PasswordInput (attrs = { ' class ' : ' C1-Control form ' }))   # widgets.PasswordInput password in ciphertext, attr increase the field

Integrated Case

# Rear 
# define form class 
class the MyForm (forms.Form): 
    name = forms.CharField (MAX_LENGTH =. 6 , 
                           label = ' username ' ,   # distal label tag label attribute values obtained 
                           error_messages, = {
                                             ' MAX_LENGTH ' : ' username longest 6 ' ,
                                             ' required ' : ' a user name can not be empty ' 
                                        }   #Custom error message, can be changed into Chinese 
                         ) 
    
DEF REG (Request):
     # generates an empty object 
    form_obj = the MyForm ()
     IF request.method == ' the POST ' : 
        form_obj = the MyForm (of request.POST)   # of request.POST is a dictionary, automatically checking incoming data, and a data error occurs is not clear 
        IF form_obj.is_valid (): 
            models.User.objects.create ( ** form_obj.cleaned_data)   # using the model table form component data checking time, just to ensure consistent field 
        so when you create an object directly ** form_obj.cleaned_data
     return the render (Request, ' reg.html ' , about locals ())
# 前端
<form action="" method="post" novalidate>
    {% for foo in form_obj %}
        <p>
        {{ foo.label }}{{ foo }}
        <span>{{ foo.errors.0 }}</span>  #只取第一个错误
        </p>
    {% endfor %}
    <input type="submit">
</form>

Third, the hook function

Local hook function (a single field using local parity hook function)

# Check the name field 666 appears on the error if 
DEF clean_name (Self): 
    name = self.cleaned_data.get ( ' name ' )
     IF  ' 666 '  in name: 
        self.add_error ( ' name ' , ' light is not enough to call 666 , there must be a real force! ' )
     return name # return or to add, compatibility considerations    

Global hook function (by using a plurality of verification fields global hook function)

# Parity on password and confirm_password consistent, error is inconsistent 
DEF Clean (Self): 
    password = self.cleaned_data.get ( ' password ' ) 
    confirm_password = self.cleaned_data.get ( ' confirm_password ' )
     IF  Not password == confirm_password: 
        Self .add_error ( ' confirm_password ' , " two passwords do not match! " )
     return self.cleaned_data    

Guess you like

Origin www.cnblogs.com/moonzier/p/11247109.html