1. The form component in Django component-forms component has the following functions:
1) generate HTML tags
2) Verify user data (Display Error Information)
3) HTML form submission retain the data submitted last time
4) content displayed on the initialization page
Field Verification
The previously written view function adds the submitted data to the database without verification. This is wrong!
For example, the user name must conform to a certain length. Password complexity.
The biggest function of forms components is to perform data verification.
The common practice is to write verification rules one by one without decoupling. Check rules are all in view functions.
Create a project formdemo
Modify URLs. py and add the path index.
from app01 import viewsurlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘index/‘, views.index),]
View code
Modify views. py and add the index view function.
Put the form component first into the view Function
Separate a class and separate it later
From Django. shortcuts import render # create your views here. from Django import forms # import module class demoform (forms. form): # must inherit form # Restrict data to strings. The maximum length is 32 name = forms. charfield (max_length = 32) age = forms. integerfield () # The limit is digital email = forms. emailfield () # restricted to the mailbox format def index (request): Return render (request, "index.html ")
View code
Templatesadds index.html, Which is empty.
<!DOCTYPE html>View code
Open pycharm and click Django console in the lower left corner.
Enter the following command to import the view function's demoform class
from app01.views import DemoForm
The effect is as follows:
The demoform class is used for verification and receives a dictionary. The dictionary must contain two keys: name, age, and email.
Test A Dictionary data
Run the following two commands:
form=DemoForm({"name":"xiao","age":"21","email":"[email protected]"})form.is_valid()
The result is as follows: True is output.
Explanation:
Is_valid () indicates that verification is performed. If all three keys meet the requirements, true is output.
Test 1: age does not match
Three must be established at the same time.
In demoform, the key corresponds to the left side of the equation, and the validation rule corresponds to the right side of the equation.
It has a default rule and cannot be blank
Test 2: one less field
Test 3: What about adding an additional key-value?
From the results, it is also possible to pass.
It only verifies the specified field, so the extra key value is ignored.
Web page Verification
Modify URLs. py and add the path addbook.
from app01 import viewsurlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘index/‘, views.index), path(‘addbook/‘, views.addbook),]
View code
Modify views. py and add the addbook view function. The complete code is as follows:
From Django. shortcuts import render, httpresponse # create your views here. from Django import forms # import module class userform (forms. form): # must inherit form # Restrict data to strings, minimum length 4, maximum length 12 name = forms. charfield (min_length = 4, max_length = 12) age = forms. integerfield () # limited to numbers # limited to 11 characters Tel = forms. charfield (min_length = 11, max_length = 11) def index (request): Return render (request, "index.html") def addbook (request): If request. method = "Post": # Pass post data to userform form = userform (request. post) If form. is_valid (): # verify data print ("success") else: Print ("fail") return httpresponse ("OK") return render (request, "addbook.html ")
View code
Templatesadd addbook.html
When performing form verification, you must note that the name and class attributes of the form must correspond one to one.
<! Doctype HTML> <HTML lang = "en"> View code
Webpage access add page, output information
After submission, the results are as follows:
Pycharm console output: Success
Empty form direct submission
Pycharm console output: fail
Is_valid () form. is_valid () It does two things:
1. pass data to form
2. Split the verification data into two containers.
Self. cleaned_data ={} indicates clean data.
Self. Error = {} indicates data that fails verification.
Self indicates the Instance Object of the userform class
Addbook view Functions
Def addbook (request): If request. method = "Post": Print (request. post) # Pass post data to userform form = userform (request. post) If form. is_valid (): # verify data print ("### success ###") print (form. cleaned_data) print (form. errors) else: Print ("### fail ###") print (form. cleaned_data) print (form. errors) print (type (form. errors) return httpresponse ("OK") return render (request, "addbook.html ")
View code
Submit data again
Pycharm console output:
<QueryDict: {‘tel‘: [‘12345678910‘], ‘email‘: [‘[email protected]‘], ‘name‘: [‘xiao‘], ‘age‘: [‘23‘], ‘csrfmiddlewaretoken‘: [‘wv7VhRwG4YvEO7SqE9qsMnpO4RpH1ys1KdiOrwgnrN3WRgW0IH8prXSUMCgdMz7u‘]}>###success###{‘tel‘: ‘12345678910‘, ‘age‘: 23, ‘name‘: ‘xiao‘}<class ‘django.forms.utils.ErrorDict‘>
View code
Although post sends five key values, userform only verifies three key values.
Form. cleaned_data outputs three key values.
The content output by form. errors is empty. Its type is errordict.
Else
Error Data demonstration
Modify views. py, modify userform, and add email
Django component-forms component