Django form
HTML forms are the classic way of interacting with the site. This chapter describes how to use Django to process user data submitted by the user.HTTP request
The HTTP protocol works in a "request-reply" manner. When a client sends a request, it can attach data to the request. By parsing the request, the server can obtain the data from the client and provide the specific service according to the URL.GET method
We created a search.py file in the previous project to receive the user's request:HelloWorld/HelloWorld/search.py File Code:
# - * - coding: utf-8 - * -
From django.http import HttpResponse
From django.shortcuts import render_to_response
# Form
Def search_form (request):
Return render_to_response ('search_form.html')
# Receive request data
Def search (request):
Request.encoding = 'utf-8'
If 'q' in request.GET:
Message = 'Your search for:' + request.GET ['q']. Encode ('utf-8')
Else:
Message = 'you submitted an empty form'
Return HttpResponse (message)
/HelloWorld/templates/search_form.html File Code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>python tutorial(simplidigital)</title>
</head>
<body>
<form action="/search" method="get">
<input type="text" name="q">
<input type="submit" value="search for">
</form>
</body>
</html>
/HelloWorld/HelloWorld/urls.py File Code
from django.conf.urls import url
from . import view,testdb,search
urlpatterns = [
url(r'^hello$', view.hello),
url(r'^testdb$', testdb.testdb),
url(r'^search-form$', search.search_form),
url(r'^search$', search.search),
]
Visit the address http://127.0.0.1:8000/search-form and search for the results as follows:
POST method
We used the GET method above. View display and request processing are divided into two functions.
The POST method is more commonly used when submitting data. We use this method below, and use a URL and handler functions to display both views and processing requests.
We created post.html in template:
HelloWorld/tmplates/post.html file code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Python tutorial(simplidigital.com)</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 add an rlt token to reserve the table for the result.
There is a {% csrf_token%} tag behind the table. Csrf full name is Cross Site Request Forgery. This is the function provided by Django to prevent camouflage submission. The POST method submits the form that must have this label.
Create a new search2.py file in the HelloWorld directory and use the search_post function to process the POST request:
/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)
The urls.py rule is modified as follows:
/HelloWorld/HelloWorld/urls.py File Code:
from django.conf.urls import url
from . import view,testdb,search,search2
urlpatterns = [
url(r'^hello$', view.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),
]
Visit http://127.0.0.1:8000/search-post The results are as follows:
After completing the above example, 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 | |-- view.py | |-- view.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 argument to each view function is an HttpRequest object, like the hello () function below:
from django.http import HttpResponse def hello(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, do not include the domain name-for example, "/Hello/".
|
method
|
The string representation of the HTTP method used in the request. All capital letters. For example:
if request.method == 'GET':
do_something() elif request.method == 'POST': do_something_else() |
GET
|
Such a Dictionary object containing all the HTTP GET parameters. See the QueryDict documentation.
|
POST
|
Such a Dictionary object containing all the HTTP POST parameters. See the QueryDict documentation.
Empty POST request is received by the server are also likely to occur. In other words, form form submitted requests through the HTTP POST method, but without data in the form. Therefore, you cannot use statements if request. POST to determine whether using the HTTP POST method should be used if request.method == "POST" (see the method property of the table).
Note: POST does not include file-upload information. See the FILES property.
|
REQUEST
|
For convenience, this property is a collection of GET and POST attributes, but there are special, first find the POST attribute, and then find the GET properties. Reference PHP's $_REQUEST.
For example, if you GET = {"name": "John"} and POST = {"age": '34'}, REQUEST[, "name"] is the value "John" REQUEST["age"] is the value "34".
Strongly recommend that you use GET and POST, because these properties are more explicit, and write code that is easier to understand.
|
COOKIES
|
Standard Python dictionary containing all the cookies object. Keys and values are strings. See also the 12th chapter, there are more detailed explanations about the cookies.
|
FILES
|
Such a Dictionary object that contains all uploaded files. Each Key FILES are <input type = "file" name= "and"/> value of the name attribute in the tag. Each value in the FILES at the same time is a standard Python Dictionary object, that contains the following three Keys:
· filename: Shang Pass the file name , Python String representation
· content-type: Shang Transfer files Content type
· content: Shang Within the original file Bulk density
Note: only if the request method is POST, and request page <form> enctype= "multipart/form-data" property FILES have the data. Otherwise, FILES is an empty dictionary.
|
META
|
The dictionary that contains all HTTP headers that are available. For example:
· CONTENT_LENGTH
· CONTENT_TYPE
· QUERY_STRING: The raw, unparsed Query string
· REMOTE_ADDR: DNS client IP Address
· REMOTE_HOST: End-host
· SERVER_NAME: Clothing Server host
· SERVER_PORT: Clothing Server-side
These headers prefixed by HTTP_ in the META Key, for example:
· HTTP_ACCEPT_ENCODING
· HTTP_ACCEPT_LANGUAGE
· HTTP_HOST: Send HTTP Host Head letter Card
· HTTP_REFERER: referring
· HTTP_USER_AGENT: DNS client user-agent String
· HTTP_X_BENDER: X-Bender Head letter Card
|
user
|
Is a django.contrib.auth.models.User object representing the current logged on user.
If access user is not currently logged on user will be initialized to an instance of django.contrib.auth.models.AnonymousUser.
You can pass the user's is_authenticated () method to identify whether the user logs on:
if request . user . is_authenticated():
# Do something for logged-in users.
else:
# Do something for anonymous users.
Only activated AuthenticationMiddleware in Django this property is only available when
|
session
|
The only read/write properties, representing a Dictionary object for the current session. The property is only activated when session support in Django is available. See also the 12th chapter.
|
raw_post_data
|
Raw HTTP POST data is not parsed. Advanced treatment will be useful.
|
Request object also has some useful methods:
Technique
|
Description
|
__getitem__(key)
|
Return GET/POST Key values , First take POST, After the GET 。 If the key does not exist throws KeyError. This is something we can use dictionary syntax to access HttpRequest Object. For example, ,request["foo"] Equivalent to the first request. POST["foo"] and then request. GET["foo"] operation.
|
has_key()
|
Check request. GET or request. POST is included in the parameter Key.
|
get_full_path()
|
Returns Query string of the request path. For example, "/music/bands/the_beatles/?print=true"
|
is_secure()
|
Requests are safe to return True , That is, That issue is HTTPS Request 。
|
QueryDict
The HttpRequest object, GET and POST attributes are instances of the django.http.QueryDict class.
QueryDict dictionary-like custom class to handle more value corresponding to one-touch.
QueryDict implements all the standard dictionary methods. Also includes specific methods:
Technique
|
Description
|
__getitem__
|
And standard dictionary one difference, that is, if Key corresponds to multiple Value,__getitem__ () returns the last value.
|
__setitem__
|
Set the parameter specifies a key value list (a Python list). Note: it can only be called on a mutable QueryDict objects (that is, through the copy () produces a QueryDict objects copy).
|
get()
|
If key corresponds to multiple value,get () returns the last value.
|
update()
|
Parameter can be a QueryDict or standard dictionary. And the update of the standard dictionary methods, this method adds 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()
|
And standard items of the dictionary () methods are a little different, the method uses a single-valued logic __getitem__ ():
>>>q = QueryDict('a=1&a=2&a=3')
>>>q . items()
[('a' , '3')]
|
values()
|
And the values of the standard dictionary () methods are a little different, the method uses a single-valued logic __getitem__ ():
|
In addition, QueryDict has some method, as the following table:
Technique
|
Description
|
copy()
|
Returns a copy of the object, internal implementation is to use Python standard library copy.Deepcopy (). The copy is mutable (can be changed)-that is, you can change the value of the copy.
|
getlist(key)
|
Returns all the values and parameters corresponding to the key, returned as a Python list. If the key does not exist, it returns an empty list. 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)
|
Add an item to the internal list associated with key.
|
setlistdefault(key,list)
|
And SetDefault is a little different, it accepts a list instead of a single value as parameters.
|
lists()
|
And items () is a little different, it will return all the values of the key, as a list, for example:
>>>q = QueryDict('a=1&a=2&a=3')
>>>q . lists()
[('a' , ['1', '2', '3'])]
|
urlencode()
|
Returns a formatted string in query string format (e.g., "a=2&b=3&b=5").
|
EmoticonEmoticon