This section describes how to get a dictionary:
Get (Key, default = none)
Returns the value corresponding to the key. If the key is not in the dictionary, the default value is returned. The default value is none.
1. Information about the request
Reqeust plays an important role in one of the key websites.
For details, refer to the definition in the Django. http. _ init _. py file.
The following are examples:
1) Request. Path ------/Hello/
2) request. get_host () ----- 127.0.0.1: 8080 or www.example.com
3) request. get_full_path () --/Hello /? Print = true
4) request. is_secure ()-(https) True, false
2. Request variable
Self. Get,
Self. Post,
Self. Cookies,
Self. Files = {},{},{},{},{}
Self. Path
Self. path_info
Self. Method
Self. Meta:
1) self. Meta
It mainly includes some HTTP headers
Http_referer URL data, http_user_agent client browser information. Remote_addr user IP Address
Note that the information is submitted by the client browser, so some values may not exist. If the value to be accessed
If no, an exception is thrown. Therefore, you must handle the exception yourself when using Meta. Example:
Def ua_display_good1 (request ):
Try:
UA = request. Meta ['HTTP _ user_agent ']
Failed t keyerror:
UA = 'unknown'
Return httpresponse ("your browser is % s" % UA)
Of course, a better way is to use the get function for processing.
Def ua_display_good2 (request ):
UA = request. Meta. Get ('HTTP _ user_agent ', 'unknown ')
Return httpresponse ("your browser is % s" % UA)
2) self. Get, self. Post
These two attributes are too familiar. They are similar to the dictionary but are more powerful than the dictionary.
3. Form class
1) Like models can define classes, form forms can also be defined like this. Normally
Place the form in the forms. py file of the app. An example of form is as follows:
From Django import forms
Class contactfrom (forms. Form ):
Subject = forms. charfield ()
Email = forms. emailfield (required = false)
Message = forms. charfiled ()
The equivalent HTML code is as follows:
>>> From contact. Forms import contactform
>>> F = contactform ()
>>> Print F
<Tr> <TH> <label for = "id_subject"> subject: </label> </Th> <TD> <input type = "text" name = "subject" id = "id_subject"/> </TD> </tr>
<Tr> <TH> <label for = "id_email"> Email: </label> </Th> <TD> <input type = "text" name = "email" id = "id_email"/> </TD> </tr>
<Tr> <TH> <label for = "id_message"> message: </label> </Th> <TD> <input type = "text" name = "message" id = "id_message"/> </TD> </tr>
2) As you can see, the default output mode of form is table. Django has many built-in output methods.
For example, print F. as_ul () is output as a list.
3) to access a single domain, for example, to access only subject, code F ['subobject'] is equivalent:
<Input type = "text" name = "subject" id = "id_subject"/>
4) You can use the is_valid () function to determine whether the form data is submitted correctly.
For example, because the email option has the required = false option, this option is not assigned a value and function verification is correct.
>>> F = contactform ({'subobject': 'hello', 'message': 'Nice site! '})
>>> F. is_valid ()
True
Once a bound form is created, the bound attribute of the form is true, that is, F. is_bound = true.
On the contrary, if the submitted data is not submitted, an error is automatically generated.
>>> F = contactform ({'subobject': 'hello', 'message ':''})
>>> F ['message']. Errors
[U'this field is required. ']
>>> F ['subobject']. Errors
[]
>>> F ['email ']. Errors
[]
** Each bound form instance has a dictionary consisting of a filed name and an error message.
This can be easily used to prompt user input errors.
5) cleaned_data, as shown in, the cleaned_data attribute can convert valid data
The corresponding Python type when the form is defined, for example, integerfield when the form is defined, the corresponding value is converted to int
>>> F = contactform ({'subobject': 'hello', 'email ': 'adrian @ example.com', 'message': 'Nice site! '})
>>> F. is_valid ()
True
>>> F. cleaned_data
{'Message': u'nice site! ', 'Email': u'adrian @ example.com ', 'subobject'
6) complete example:
# Views. py
From Django. Shortcuts import render_to_response
From mysite. Contact. Forms import contactform
Def contact (request ):
If request. Method = 'post ':
Form = contactform (request. Post) # If the user submits an error
# Contains the error message. When you render an error, an error message is displayed in the error submission field.
If form. is_valid ():
Cd = form. cleaned_data
Send_mail (
CD ['subobject'],
CD ['message'],
CD. Get ('email ', 'noreply @ example.com '),
['Siteowner @ example.com '],
)
Return httpresponseredirect ('/contact/Thanks /')
Else:
Form = contactform ()
Return render_to_response('contact_form.html ', {'form': form })
# Contact_form.html
<HTML>
<Head>
<Title> Contact Us </title>
</Head>
<Body>
<H1> Contact Us
{% If form. Errors %}
<P style = "color: red;">
Please correct the error {form. Errors | pluralize} below.
</P>
{% Endif %}
<Form action = "" method = "Post">
<Table>
{Form. as_table }}
</Table>
<Input type = "Submit" value = "Submit">
</Form>
</Body>
</Html>
4. Custom forms
Each field has a default representation. Of course, you can customize the desired representation.
1) form attributes
From Django import forms
Class contactform (forms. Form ):
Subject = forms. charfield (max_length = 100, min_length = 10)
Email = forms. emailfield (required = false)
Message = forms. charfield (widget = forms. textarea )#######
2) form Default Value
Form = contactfrom (
Incircle = {"subject": 'I love your site '}
)
3) custom verification rules
From Django import forms
Class contactform (forms. Form ):
Subject = forms. charfield (min_length = 10)
Email = forms. emailfield (required = false)
Message = forms. charfield (widget = forms. textare)
Def clean_message (Self): # the first name of the function to be verified is clean _, and the last one is the field name.
# Self-defined authentication message, only after passing the default Verification
Message = self. cleand_data ['message'] # self-defined verification only adds something based on the default verification.
Num_words = Len (message. Split ())
If num_words <4:
Raise forms. validationerror ('not enougth words! ')
Return message # Never forget the statement. Otherwise, even if the verification is OK, none is returned.
4) Specify the label name.
Like verbose_name of models, form can also specify its own label name
From Django import forms
Class contactform (forms. Form ):
Subject = forms. charfield (min_length = 10, label = 'your subobject ')
Email = forms. emailfield (required = false, label = 'your email ')
Message = forms. charfield (widget = forms. textare)
5) Form Format
You can easily modify the form style through CSS. For example, when the form is filled incorrectly, the error list is displayed.
<Style type = "text/CSS">
Ul. errorlist {
Margin: 0;
Padding: 0;
}
. Errorlist Li {
Background-color: red;
Color: white;
Display: block;
Font-size: 10px;
Margin: 0 0 3px;
Padding: 4px 5px;
}
</Style>
Similarly, because each form field can be accessed through {form. fieldname}, the error of each field
Can be accessed through {form. fieldname. Errors}., so you can make powerful customization as needed.
<End of this section>