The module forms Django
Providing modules in Django forms, forms with the inside of the module may be automatically generated form form controls, while operating the client may receive and form elements in the form of an object on the server side, the server side authentication and can be a form of data
An action module forms
In the forms module, and a form to allow the combination of class, allows the generation of a form class by
To use two forms of modules
1. Create forms.py in the application
2. Import forms django provided
from django import forms
3. Create class, a class will generate a form
# Define the form class class ClassName (forms.Form): ...
4. Create a class attributes in the class
A class attribute is mapped to a control form
The type of an object automatically to the use of Form Form Content
6. Read and verify data form form
Three form.Form syntax
= Forms.Field type attribute (parameter)
1. Type
class XXX (froms.Form): forms.CharField (): text box <the INPUT of the type = " text " > forms.ChoiceField (): drop-down selection box <the SELECT> forms.DateField (): date box <the INPUT of the type = " DATE " > ... ...
2. Parameters
- Text front controls: label
- widget: widget specified
- initial: initial value of the control (mainly for text box type)
- required: whether it is required, the value (True / False)
form form example
Done manually Form Form
<form action="/test_form1" method="post"> <div> <label for="id_input_text">请输入内容:</label> <input type="text" name="input_text" id="id_input_text" /> </div> <button type="submit">提交</button> </form>
Django Form Form Form realize
class the MySearch (forms.Form): the input_text = forms.CharField (label = " Please enter Content ' )
Four objects in analytic form templates
1. Methods
You need to customize
The form required to customize buttons
2. Parse from objects
Analytical form template created and sent to an object in view. EX: form = XXXForm () return the render (Request, ' xx.html ' , about locals ())
(1) Analytical Manual {% for field in form%}
field: represents the form object for each property (control)
{{Field.label}}: label parameter values is represented by
{{Field}}: control is represented by
{% endfor %}
(2) automatically parse
{{form.as_p}} 将form中的每个属性(控件/文本)都使用p标记包裹起来再显示
{{Form.as_ul}} The form of each attribute (control / text) are then wrapped using li tag display
Note: You must provide ol or ul tags manually
{{Form.as_table}} The form of each attribute (control / text) uses tr tag wrapped redisplay
Note: You must manually mark provided table
Five get form data through forms objects
1. The data received by the post subclass constructor forms.Form
form = XXXForm(request.POST)
2. The form must be verified by the order value
form.is_valid()
Returns True: validation, you can take the values
Returns False: Write validated, the value can not be
3. By receiving the attribute data dictionary form.cleaned_data
form.cleaned_data : dict 类型
Field built six widgets - widget
1. What is the widget
Representation is to generate a control on the page and some other html attributes
message=forms.CharField(widget=forms.Textarea)
upwd=forms.CharField(widget=forms.PasswordInput)
2. Common types of widget
widget name | Class value corresponding to the type and |
TextInput | type='text' |
PasswordInput | type='password' |
NumberInput | type="number" |
EmailInput | type="email" |
URLInput | type="url" |
HiddenInput | type="hidden" |
CheckboxInput | type="checkbox" |
CheckboxSelectMultiple | type="checkbox" |
RadioSelect | type="radio" |
Textarea | textarea tag |
Select | select mark |
SelectMultiple | select multiple markers |
3. Use widget
(1) inherited sub forms.Form
grammar
Forms.CharField property = () # no preselected value using text, password, email, url, textarea, checkbox property = forms.ChoiceField () # with a preselected value using the checkbox, radio, select attributes = forms.CharField ( label = ' XXX ' , the widget = Forms. widget type )
Examples
= upwd forms.CharField ( label = ' user password ' , the widget = forms.PasswordInput ) the Message = forms.CharField ( label = ' Review ' , the widget = forms.Textarea )
See the documentation https://docs.djangoproject.com/en/1.11/topics/forms/
Seven form form validation
django form provides verification forms and fields
When creating the site has a plurality of different forms to be submitted, with a more convenient form validation package validation
When you call form.is_valid () returns True if the current form legitimate, when it returns False Description form validation problems
Verification steps:
1. First of () parameter values form.XXXField verify, for example: min_length, max_length, validators = [...], if it does not form.is_valid () returns False
2. For each attribute name from.clean_zzz (self): The method of verification of the corresponding attribute, if the verification fails form.is_valid () returns False
3. The transfer armpit form.clean (self): the overall structure of the form is, if validation fails form.is_valid () returns False
4. Verify above all successful form.is_valid () returns True
Authentication method:
validators = [a verification function, verification function 1]
Validation function verification fails throw forms.ValidationError
Verify successful return None
def clean_xxx property (self):
Validation failure must throw forms.ValidationError
Verify success must return the value of the property xxx
def clean(self):
Validation failure must throw forms.ValidationError
Verify success must return self.cleaned_data
from Django Import Forms Import Re mobile_re = the re.compile (R & lt ' ^ (13 is [0-9] | 15 [012 356 789] |. 17 [678] | 18 is [0-9] | 14 [57 is]) [0-9] $. 8} { ' ) DEF mobile_validate (value): IF Not mobile_re.match (value): The raise forms.ValidationError ( ' phone number format error ' ) class RegisterForm (forms.Form): username = forms.CharField (label = ' username ' ) password = forms.CharField (label = ' Please input password ' , the widget =forms.PasswordInput) password2 = forms.CharField (label = ' re-enter the new password ' , the widget = forms.PasswordInput) Mobile = forms.CharField (label = ' phone number ' , validators = [mobile_validate]) DEF Clean (Self): pwd1 = self.cleaned_data [ ' password ' ] pwd2 = self.cleaned_data [ ' password2 ' ] IF pwd1 =! pwd2: The raise forms.ValidationError ( ' two passwords do not match! ' ) return self.cleaned_data # 必须返回cleaned_data def clean_username(self): username = self.cleaned_data['username'] if len(username) < 6: raise forms.ValidationError("用户名太短") return username