Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django Forms

Django Forms

HTML forms are a classic way for websites to be interactive. This chapter introduces how to process form data submitted by users with Django.


HTTP request

The HTTP protocol works in a "request-response" manner. When a client sends a request, it can attach data to the request. By parsing the request, the server can obtain the data sent by the client and provide specific services based on the URL.

GET Method

We create a search.py file in the previous project to receive user requests:

/HelloWorld/HelloWorld/search.py file code:

from

django

.

http

import

HttpResponse

from

django

.

shortcuts

import

render

The form

def

search_form

(

request

)

:

return

render

(

request

,

'

search_form.html

'

)

Receive request data

def

search

(

request

)

:

request

.

encoding

=

'

utf-8

'

if

'

q

'

in

request

.

GET

and

request

.

GET

[

'

q

'

]

:

message

=

'

What you searched for is:

'

request

.

GET

[

'

q

'

]

else

:

message

=

'

You submitted an empty form

'

return

HttpResponse

(

message

)

Add a search_form.html form in the templates directory:

/HelloWorld/templates/search_form.html file code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>

Runoob Tutorial(runoob.com)

title

head

<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search" form body html>

Modify the urls.py rules to the following form:

/HelloWorld/HelloWorld/urls.py file code:

from

django

.

conf

.

urls

import

url

from

.

import

views

,

testdb

,

search

urlpatterns

=

[

url

(

r

'

^hello/$

'

,

views

.

runoob

)

,

url

(

r

'

^testdb/$

'

,

testdb

.

testdb

)

,

url

(

r

'

^search-form/$

'

,

search

.

search_form

)

,

url

(

r

'

^search/$

'

,

search

.

search

)

,

]

Address accessed http://127.0.0.1:8000/search-form/ and search; the result is as follows:

POST Method

Above we used the GET method, with view display and request handling split into two functions.

The POST method is more commonly used when submitting data. We use this method below, with one URL and one handler function that both displays the view and handles the request.

We create post.html in templates:

/HelloWorld/templates/post.html file code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>

Runoob Tutorial(runoob.com)

title

head

<body>
<form action="/search-post/" method="post">

{% csrf_token %}

<input type="text" name="q">
<input type="submit" value="Search" form>
<p>

{{ rlt }}

p

body

html

At the end of the template, we add an rlt marker to reserve a place for the table processing result.

After the form there is also a {% csrf_token %} tag. csrf stands for Cross Site Request Forgery. This is a feature provided by Django to prevent forged submitted requests. Forms submitted with the POST method must have this tag.

Create a new search2.py file in the HelloWorld directory and use the search_post function to handle POST requests:

/HelloWorld/HelloWorld/search2.py file code:

-- coding: utf-8 --

from

django

.

shortcuts

import

render

from

django

.

views

.

decorators

import

csrf

Receive POST request data

def

search_post

(

request

)

:

ctx

={}

if

request

.

POST

:

ctx

[

'

rlt

'

]

=

request

.

POST

[

'

q

'

]

return

render

(

request

,

"

post.html

"

,

ctx

)

Modify the urls.py rules to the following form:

/HelloWorld/HelloWorld/urls.py file code:

from

django

.

conf

.

urls

import

url

from

.

import

views

,

testdb

,

search

,

search2

urlpatterns

=

[

url

(

r

'

^hello/$

'

,

views

.

hello

)

,

url

(

r

'

^testdb/$

'

,

testdb

.

testdb

)

,

url

(

r

'

^search-form/$

'

,

search

.

search_form

)

,

url

(

r

'

^search/$

'

,

search

.

search

)

,

url

(

r

'

^search-post/$

'

,

search2

.

search_post

)

,

]

Access the http://127.0.0.1:8000/search-post/ The display result is as follows:

After completing the above examples, our directory structure is:



HelloWorld

|-- HelloWorld

|   |-- __init__.py

|   |-- __init__.pyc

|   |-- search.py

|   |-- search.pyc

|   |-- search2.py

|   |-- search2.pyc

|   |-- settings.py

|   |-- settings.pyc

|   |-- testdb.py

|   |-- testdb.pyc

|   |-- urls.py

|   |-- urls.pyc

|   |-- views.py

|   |-- views.pyc

|   |-- wsgi.py

|   `-- wsgi.pyc

|-- TestModel

|   |-- __init__.py

|   |-- __init__.pyc

|   |-- admin.py

|   |-- admin.pyc

|   |-- apps.py

|   |-- migrations

|   |   |-- 0001_initial.py

|   |   |-- 0001_initial.pyc

|   |   |-- __init__.py

|   |   `-- __init__.pyc

|   |-- models.py

|   |-- models.pyc

|   |-- tests.py

|   `-- views.py

|-- db.sqlite3

|-- manage.py

`-- templates

    |-- base.html

    |-- hello.html

    |-- post.html

    `-- search_form.html


Request Object

The first parameter of every view function is an HttpRequest object, just like the following runoob() function:



from django.http import HttpResponse



def runoob(request):

    return HttpResponse("Hello world")

The HttpRequest object contains some information about the current request URL:

property

Description

path

The full path of the requested page, excluding the domain name - for example, "/hello/".

method

A string representation of the HTTP method used in the request. In all uppercase. For example:

if request.method == 'GET':


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

| |

GET

|

A dictionary-like object containing all HTTP GET parameters. See the QueryDict documentation.

| |

POST

|

A dictionary-like object containing all HTTP POST parameters. See the QueryDict documentation.

It is also possible for the server to receive an empty POST request. That is, a form submits a request via the HTTP POST method, but the form may contain no data. Therefore, you cannot use the statement if request.POST to determine whether the HTTP POST method is used; you should use if request.method == "POST" (see the method attribute in this table).

Note: POST does not include file-upload information. See the FILES attribute.

| |

REQUEST

|

For convenience, this attribute is a combination of the POST and GET attributes, but with a special feature: it searches the POST attribute first, then the GET attribute. Borrowed from PHP's $_REQUEST.

For example, if GET = {"name": "john"} and POST = {"age": '34'}, then the value of REQUEST["name"] is "john" and the value of REQUEST["age"] is "34".

It is strongly recommended to use GET and POST, because these two attributes are more explicit and make the code easier to understand.

| |

COOKIES

|

A standard Python dictionary object containing all cookies. Keys and values are both strings.

| |

FILES

|

A dictionary-like object containing all uploaded files. Each Key in FILES is thevalue of the name attribute in the tag. Each value in FILES is also a standard Python dictionary object containing the following three Keys:

Note: Only when the request method is POST and the request page has

the enctype="multipart/form-data" attribute does FILES have data. Otherwise, FILES is an empty dictionary.

| |

META

|

A dictionary containing all available HTTP header information. For example:

  • CONTENT_LENGTH
  • CONTENT_TYPE
  • QUERY_STRING: The raw, unparsed query string
  • REMOTE_ADDR: The client's IP address
  • REMOTE_HOST: The client's hostname
  • SERVER_NAME: The server's hostname
  • SERVER_PORT: The server's port

These headers in META with the prefix HTTP_ as the Key, and the part after the colon (:) as the Value, for example:

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

user

|

is a django.contrib.auth.models.User object representing the currently logged-in user.

If the visiting user is not currently logged in, user will be initialized as an instance of django.contrib.auth.models.AnonymousUser.

You can use the user's is_authenticated() method to tell whether a user is logged in:

if request.user.is_authenticated():

    # Do something for logged-in users.

else:

    # Do something for anonymous users.

This attribute is only available when AuthenticationMiddleware is enabled in Django

| |

session

|

The only readable and writable attribute, a dictionary object representing the current session. This attribute is only available when session support is enabled in Django.

| |

raw_post_data

|

Raw HTTP POST data, unparsed. Useful for advanced processing.

|

The Request object also has some useful methods:

Method Description
getitem(key) Returns GET/POST key values, taking POST first, then GET. Raises KeyError if the key does not exist.
 这是我们可以使用字典语法访问HttpRequest对象。       

 例如,request["foo"]等同于先request.POST["foo"] 然后 request.GET["foo"]的操作。 |

| has_key() | Checks whether request.GET or request.POST contains the Key specified by the parameter. | | get_full_path() | Returns the request path including the query string. For example, "/music/bands/the_beatles/?print=true" | | is_secure() | Returns True if the request is secure, that is, an HTTPS request was made. |

QueryDict object

In the HttpRequest object, the GET and POST attributes are instances of the django.http.QueryDict class.

QueryDict is a custom dictionary-like class used to handle the case where a single key corresponds to multiple values.

QueryDict implements all standard dictionary methods. It also includes some specific methods:

Method Description

getitem

There is a slight difference from standard dictionary handling: if a Key corresponds to multiple Values,getitem() returns the last value.

setitem

Sets the list of values (a Python list) for the specified key. Note: it can only be called on a mutable QueryDict object (a copy of a QueryDict object produced by copy()).

get()

If a key corresponds to multiple values, get() returns the last value.

update()

The parameter can be a QueryDict or a standard dictionary. Unlike the update method of a standard dictionary, this method adds dictionary items instead of replacing 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 is a slight difference from the standard dictionary's items() method: this method uses the single-value logic of __getitem__():

>>> q = QueryDict('a=1&a=2&a=3')

>>> q.items()

[('a', '3')]

| |

values()

|

There is a slight difference from the standard dictionary's values() method: this method uses the single-value logic of __getitem__():

|

In addition, QueryDict also has some methods, as shown in the following table:

Method Description

copy()

Returns a copy of the object, internally implemented using copy.deepcopy() from the Python standard library. The copy is mutable - that is, you can change the values in the copy.

getlist(key)

Returns all values corresponding to the parameter key as a Python list. If the key does not exist, an empty list is returned. It's guaranteed to return a list of some sort..

setlist(key,list_)

Sets the value of key to list_ (unlike setitem()).

appendlist(key,item)

Adds an item to the internal list associated with key.

setlistdefault(key,list)

There is a slight difference from setdefault: it accepts a list rather than a single value as a parameter.

lists()

There is a slight difference from items(): it returns all values of a key as a list, for example:

>>> q = QueryDict('a=1&a=2&a=3')

>>> q.lists()

[('a', ['1', '2', '3'])]

| |

urlencode()

|

Returns a string formatted in query string format (for example: "a=2&b=3&b=5").

|