Django forms
HTML forms are the classic way interactive website. This chapter explains how to deal with Django form data submitted by a user.
HTTP request
HTTP protocol "Request - Reply" manner. When the client sends a request, you may request additional data. Server resolution request, you can get data from the client, and to provide specific services based on URL.
GET Method
We created a search.py file before the project, for receiving a user request:
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response # 表单 def search_form(request): return render_to_response('search_form.html') # 接收请求数据 def search(request): request.encoding='utf-8' if 'q' in request.GET: message = '你搜索的内容为: ' + request.GET['q'].encode('utf-8') else: message = '你提交了空表单' return HttpResponse(message)
Add search_form.html form template in the template directory:
<html> <head> <meta charset="utf-8" /> <title>Search - w3cschool.cc</title> </head> <body> <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>
urls.py rule is amended as follows:
from django.conf.urls import * from HelloWorld.view import hello from HelloWorld.testdb import testdb from HelloWorld import search urlpatterns = patterns("", ('^hello/$', hello), ('^testdb/$', testdb), (r'^search-form/$', search.search_form), (r'^search/$', search.search), )
Access address: http: //192.168.45.3: 8000 / search-form / and search, the results are as follows:
POST method
Above we used the method GET. View display and request processing functions into two treatment.
More commonly POST method to submit data. We use the following this method, with a URL and handlers, also shows the view and process the request.
We created post.html in tmplate:
<html> <head> <meta charset="utf-8" /> <title>Search - w3cschool.cc</title> </head> <body> <form action="/search-post/" method="post"> {% csrf_token %} <input type="text" name="q"> <input type="submit" value="Submit"> </form> <p>{{ rlt }}</p> </body> </html>
At the end of the template, we added a rlt mark placeholder for the table results.
There is also a table {% csrf_token%} tag later. csrf stands for Cross Site Request Forgery. This is provided by Django prevent forgery submit requests. POST method to submit the form, you must have this label.
New search2.py file in the HelloWorld directory and use search_post function to handle POST requests:
# -*- coding: utf-8 -*- from django.shortcuts import render from django.core.context_processors import csrf # 接收POST请求数据 def search_post(request): ctx ={} ctx.update(csrf(request)) if request.POST: ctx['rlt'] = request.POST['q'] return render(request, "post.html", ctx)
urls.py rule is amended as follows:
from django.conf.urls import * from HelloWorld.view import hello from HelloWorld.testdb import testdb from HelloWorld import search from HelloWorld import search2 urlpatterns = patterns("", ('^hello/$', hello), ('^testdb/$', testdb), (r'^search-form/$', search.search_form), (r'^search/$', search.search), (r'^search-post/$', search2.search_post), )
Access http://192.168.45.3:8000/search-post/ Display results as follows:
After completion of the above examples, our directory structure:
HelloWorld |-- HelloWorld | |-- __init__.py | |-- __init__.pyc | |-- models.pyc | |-- search.py | |-- search.pyc | |-- search2.py | |-- search2.pyc | |-- settings.py | |-- settings.pyc | |-- testdb.py | |-- testdb.pyc | |-- urls.py | |-- urls.pyc | |-- view.py | |-- view.pyc | |-- wsgi.py | `-- wsgi.pyc |-- TestModel | |-- __init__.py | |-- __init__.pyc | |-- admin.py | |-- models.py | |-- models.pyc | |-- tests.py | `-- views.py |-- manage.py `-- templates |-- base.html |-- hello.html |-- post.html `-- search_form.html 3 directories, 29 files
Request Object
Each view function the first argument is an HttpRequest object, just below the hello () function:
from django.http import HttpResponse def hello(request): return HttpResponse("Hello world")
HttpRequest object contains some information about the current request URL:
Attributes | description |
path | The full path to the requested page, not including the domain name - for example, "/ hello /". |
method | String HTTP method used in the request representation. It represents all uppercase. E.g: if request.method == 'GET': |
GET | It contains all HTTP GET parameters dictionary-like object. See QueryDict documentation. |
POST | It contains all the HTTP POST parameters dictionary-like object. See QueryDict documentation. Situation POST request server receives empty is also possible. In other words, the form form to submit a request via HTTP POST method, but can not form data. Therefore, the statement can not be used if request.POST to determine whether to use the HTTP POST method; you should use if request.method == "POST" (see this table method attribute). Note: POST does not include file-upload information. See FILES properties. |
REQUEST | For convenience, this property is a collection of POST and GET attribute, but there particularity, checking POST first property, then look GET attribute. Reference PHP's $ _REQUEST. For example, if you GET = { "name": "john"} and POST = { "age": '34'}, then REQUEST [ "name"] value is "john", [ "age"] the value of REQUEST is "34." It is strongly recommended to use GET and POST, because these two attributes of a more explicit, written the code easier to understand. |
COOKIES | All cookies contain standard Python dictionary object. Keys and values are strings. See Chapter 12, there is a more detailed explanation about cookies. |
FILES | Dictionary-like object containing all uploaded files. . FILES Each Key is <input type = "file" name = "" /> tag name attribute value FILES each value is also a standard Python dictionary object that contains the following three Keys:
Note: Only the request method is POST, and the request page <form> has enctype = "multipart / form-data" attribute FILES only have data. Otherwise, FILES is an empty dictionary. |
META | Containing all available HTTP headers dictionary. E.g:
META these headers prefixed HTTP_ most Key, for example:
|
user | Django.contrib.auth.models.User is an object that represents the user currently logged on. If you access the user is currently not logged in, user will be initialized instance of django.contrib.auth.models.AnonymousUser. You can be identified by the user's is_authenticated () method of a user is logged: if request.user.is_authenticated(): # Do something for logged-in users. else: # Do something for anonymous users. Django activated only when the AuthenticationMiddleware The property is available |
session | The only writable property that represents the current session of the dictionary object. Django activated only when the session supported the property is available. See Chapter 12. |
raw_post_data | Raw HTTP POST data, not parsed. Be useful when advanced treatment. |
Request object also has some useful methods:
method | description |
---|---|
__getitem __ (key) | Returns the GET / POST keys, first take POST, after taking GET. If the key does not exist throw KeyError. This is what we can use dictionary syntax to access HttpRequest object. For example, request [ "foo"] is equivalent to the first request.POST [ "foo"] then request.GET [ "foo"] operation. |
has_key () | Check request.GET or request.POST parameter specifies whether to include the Key. |
get_full_path () | Return path request contains a query string. For example, "/ music / bands / the_beatles /? Print = true" |
is_secure () | If the request is safe, return True, that is, the light emitted is HTTPS requests. |
QueryDict objects
In HttpRequest object, GET and POST attributes are instances django.http.QueryDict class.
QueryDict similar custom dictionary class to handle the case of multi-value corresponding to a single bond.
QueryDict implement all the standard dictionary methods. The method also includes specific:
method | description |
---|---|
__getitem__ | Standard dictionary process is a little different, that is, if the corresponding number of Key Value, __ getitem __ () returns the last value. |
__setitem__ | Setting parameter specifies the value of a list of key (a Python list). Note: It can only be called (copy is through the copy () generated a QueryDict object) on a mutable QueryDict object. |
get () | If the key corresponding to the plurality of value, get () returns the last value. |
update () | Parameters can be QueryDict, it can be a standard dictionary. Different standard dictionary update method and the method of adding the dictionary items, rather than replace them: >>> q = QueryDict('a=1') >>> q = q.copy() # to make it mutable >>> q.update({'a': '2'}) >>> q.getlist('a') ['1', '2'] >>> q['a'] # returns the last ['2'] |
items () | There are the standard dictionary items () method is a little different, the method uses a single-valued logic __getitem __ (): >>> q = QueryDict('a=1&a=2&a=3') >>> q.items() [('a', '3')] |
values () | The standard dictionary values () method is a little different, the method uses a single-valued logic __getitem __ (): |
In addition, QueryDict there are some methods, the following table:
method | description |
---|---|
copy () | Returns a copy of the object, the internal implementation in Python standard library copy.deepcopy (). This copy is mutable (changeable) - that is, you can change the value of the copy. |
getlist (key) | All the parameters and return values of the corresponding key, as a Python list returned. If the key does not exist, it returns an empty list. It's guaranteed to return a list of some sort .. |
setlist (key, list_) | Set key value list_ (unlike __setitem __ ()). |
appendlist (key, item) | Add the item to the key and the associated internal list. |
setlistdefault (key, list) | And setdefault a little different, it accepts list rather than a single value as an argument. |
lists () | And items () is a little different, it will return all of the key values, as a list, for example: >>> q = QueryDict('a=1&a=2&a=3') >>> q.lists() [('a', ['1', '2', '3'])] |
urlencode () | Returns a string formatted to perform the query string format (eg, "a = 2 & b = 3 & b = 5"). |