Document directory
FormsHTML form is the pillar of interactive web pages. The following describes how to use Django to process the form data submitted by users, and perform verification. We will discuss HttpRequest and Form objects.
- Information contained in the request
In views. py, each function used to display the page must use request as the first function parameter. The request contains some useful
For example, request. path removes the access path of the domain name and port, request. get_host domain name + port information request. get_full_path () All paths, including the passed parameter requets. whether is_secure () uses https for link has a special attribute request. META. It is a dict type that contains all HTTP header information, but it must be determined based on the user's actual environment. For example, HTTP_REFERERHTTP_USER_AGENT indicates the user's browser information REMOTE_ADDR. If a proxy is used, it can be displayed (with many attributes, but only some). Not all headers submitted by each user are the same, therefore, when reading data, consider some exceptions, such as the failure to obtain the corresponding value. You can use try... try t or dict. get (key, default) to return the default value. Def ua_display_good1 (request): try: ua = request. META ['HTTP _ USER_AGENT '] doesn t KeyError: ua = 'unknown' return HttpResponse ("Your browser is % s" % ua) def ua_display_good2 (request): ua = request. META. get ('HTTP _ USER_AGENT ', 'unknown') return HttpResponse ("Your browser is % s" % ua) except for the above metadata information, the HttpRequest object also includes two attributes: request. GET and request. POST. They are all dictionary-like objects. That is to say, you can operate like dict, but not dict. There are still some operations that dict does not have. The following is a simple form example for user search. # Template/search_form.html <
Form
Action= "/Search /"
Method= "Get">
<
Input
Type= "Text"
Name= "Q">
<
Input
Type= "Submit"
Value= "Search">
</
Form> # Template/search_results.html <
P> Your searched for '{query }}'
{% If books %}
{% For book in books %}
<
Li> {Book.
Title}}</
Li>
{% Endfor %}
{% Else %}
<
P> No books found.
{% Endif %} # urls. py
FromDjango. conf. urls
ImportPatterns, include, url
FromBooks. views
ImportHello, search_form,
Search
Urlpatterns = patterns ('',
Url (R' ^ search-form/$ ', search_form ),
Url (R' ^ search/$ ',
Search),
)
# Views. py
FromDjango. http
ImportHttpResponse
FromDjango. shortcuts
ImportRender_to_response
FromBooks. models
ImportBook
DefSearch_form (request ):
ReturnRender_to_response('search_form.html ')
Def Search(Request ):
If'Q'InRequest. GET: # GET is a dict. The name of the text box is used as the key.
# Here we need to make a judgment to check whether data is submitted to avoid an error.
Q = request. GET ['q']
# Use The lookup suffix, which means that the title is case-insensitive and can contain q.
Books = Book. objects.Filter(Title _ icontains = q)
ReturnRender_to_response('search_results.html ', {'books': books, 'query': q })
Else:
Message = 'you submitted an empty form .'
# Simply return a response object. Because no module is used, you do not need to render the data Context.
ReturnAnother point is HttpResponse (message). If the action attribute in form is empty, data is submitted to the current page. Form verification can be performed on the server, sometimes increasing the burden on the server, or using Javascript on the client. One thing to note is that even if you have used javascript For verification on the client, you still need to review the data submitted by the user on the server side. For example, some people Disable javascript in the browser, some may launch injection attacks. In short, you cannot trust the Submission submitted by the user for defensive encoding. With regard to redirection, you should always perform redirect after a POST request is successfully processed. This can avoid the problem of secondary requests caused by multiple clicks of the submit button, and sometimes cause bad consequences, such as inserting duplicate records into the database. From django. http import HttpResponseRedirect
Return HttpResponseRedirect ('/success /')
- Use Django's form system to simplify form work
Create forms in the app folder. py, in fact, can be created anywhere: from django import forms class ContactForm (forms. form): subject = forms. charField () email = forms. emailField (required = False) message = forms. the definition of CharField () form is similar to that of the model class. We can use python manage. py shell to view the form class information. The printed f information is actually in the webpage format. You can also change the format of the default table. <Table> and <ul> are not included in the output, so you can add rows freely. In addition to printing the HTML content of the entire form, you can also print out the content of the field. You can also use the form class for verification and dict to initialize the form class. >>> F = ContactForm ({'subobject': 'hello', 'email ': 'adrian @ example.com', 'message': 'Nice '}) >>> f. is_bound # Whether to bind the Form class True >>> f. is_valid () # whether the data content is legal True when all the data is legal, you can use the clean_data attribute to obtain the data formatted by 'clean, the data submitted by the club is converted to the appropriate Python type. How to Use form class # views. py in view
FromDjango. shortcutsImportRender_to_response
FromMysite. contact. formsImportContactForm
DefContact (request ):# You can leave it empty, because the variables defined in if in python can also be seen in the entire function.Form =None
IfRequest. method = 'post ':
Form = ContactForm (request. POST)
IfForm. is_valid ():
Cd = form. cleaned_data
Send_mail (
Cd ['subobject'],
Cd ['message'],
Cd. get ('email ', 'noreply @ example.com '),
['Siteowner @ example.com '],
)
ReturnHttpResponseRedirect ('/contact/thanks/') # configure the path in urls. py.
Else:
Form = ContactForm ()
ReturnRender_to_response('contact_form.html ', {'form': form}) # contact_form.html <Html>
<Head>
<Title> Contact us </Title>
</Head>
<Body>
<H1> Contact us </H1>
{% IfForm. Errors %}
<P Style= "Color: red;" >{# pulralize is a filter used to determine whether to add 's' To indicate the plural form of a word #}
Please correct the error {{Form. Errors | pluralize} below.
</P>
{% Endif %}
<Form Action= ""Method= "Post">
<Table>
{# You can use as_ul and as_p to change the format #}
{{Form. As_table }}
</Table>
<Input Type= "Submit"Value= "Submit">
</Form>
</Body>
</Html> When constructing a form, you can also change the construction parameters of fields.ClassContactForm (forms. Form ):
Subject = forms. CharField (max_length = 100)
Email = forms. EmailField (required =False)
Message = forms. CharField (widget = forms. Textarea) You can also add the default form = ContactForm (initial = {'subobject': 'I love your site! '}) Customize verification rules for the form class. If you want to reuse the verification mechanism, you can create a new field class and rewrite its verification method. Generally, you can directly add the clean _ field name to the form class. Django will automatically find the function name starting with clean _ and run this function when verifying the field.FromDjangoImportForms
ClassContactForm (forms. Form ):
Subject = forms. CharField (max_length = 100)
Email = forms. EmailField (required =False)
Message = forms. CharField (widget = forms. Textarea)
DefClean_message (Self):
Message =Self. Cleaned_data ['message']
Num_words =Len(Message. split ())
IfNum_words <4:
RaiseForms. ValidationError ("Not enough words! ")
ReturnMessage in the Custom verification function, we must display the content of the returned field name, otherwise it will cause the loss of form data. You can change the name displayed by the field label email = forms. EmailField (required = False, label = 'your e-mail address ')
Publish by note