Latest web development tutorials

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 ​​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):  
	if 'q' in request.GET:
		message = '你搜索的内容为: ' + request.GET['q'].encode('utf-8')
		message = '你提交了空表单'
	return HttpResponse(message)

Add search_form.html form template in the template directory:

	<meta charset="utf-8" /> 
    <title>Search -</title>
    <form action="/search/" method="get">
        <input type="text" name="q">
        <input type="submit" value="Search">
</html> 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),

Access address: http: // 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:

	<meta charset="utf-8" /> 
    <title>Search -</title>
	<form action="/search-post/" method="post">
		{% csrf_token %}
		<input type="text" name="q">
		<input type="submit" value="Submit">

	<p>{{ rlt }}</p>

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 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 ={}
	if request.POST:
		ctx['rlt'] = request.POST['q']
	return render(request, "post.html", ctx) 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-post/$', search2.search_post),

Access Display results as follows:

After completion of the above examples, our directory structure:

|-- HelloWorld
|   |--
|   |-- __init__.pyc
|   |-- models.pyc
|   |--
|   |-- search.pyc
|   |--
|   |-- search2.pyc
|   |--
|   |-- settings.pyc
|   |--
|   |-- testdb.pyc
|   |--
|   |-- urls.pyc
|   |--
|   |-- view.pyc
|   |--
|   `-- wsgi.pyc
|-- TestModel
|   |--
|   |-- __init__.pyc
|   |--
|   |--
|   |-- models.pyc
|   |--
|   `--
`-- 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:




The full path to the requested page, not including the domain name - for example, "/ hello /".


String HTTP method used in the request representation. It represents all uppercase. E.g:

if request.method == 'GET':
do_something ()
elif request.method == 'POST':
do_something_else ()


It contains all HTTP GET parameters dictionary-like object. See QueryDict documentation.


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.


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.


All cookies contain standard Python dictionary object. Keys and values ​​are strings. See Chapter 12, there is a more detailed explanation about cookies.


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:

  • filename: Upload a file name with a string representation of Python
  • Content type of the uploaded file: content-type
  • Original content uploaded file: content

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.


Containing all available HTTP headers dictionary. E.g:

  • QUERY_STRING: unresolved original query string
  • REMOTE_ADDR: IP address of the client
  • REMOTE_HOST: client host name
  • SERVER_NAME: Server Host Name
  • SERVER_PORT: server port

META these headers prefixed HTTP_ most Key, for example:

  • HTTP_HOST: HTTP host header information sent by the client
  • HTTP_REFERER: referring page
  • HTTP_USER_AGENT: the client's user-agent string
  • HTTP_X_BENDER: X-Bender header


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.
    # Do something for anonymous users.

Django activated only when the AuthenticationMiddleware The property is available


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 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


Standard dictionary process is a little different, that is, if the corresponding number of Key Value, __ getitem __ () returns the last value.


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


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").