7.7. Django form
Release time :2025-11-25 20:32:25 UTC
Page Views: 1 views
HTML forms are a classic way to interact with a website. This chapter describes how to use Django to process form data submitted by users.
7.7.1. HTTP request ¶
The HTTP protocol works in a request-reply manner. When a customer sends a request, data can be attached to the request. By parsing the request, the server can get the data sent by the customer and provide specific services according to the URL.
7.7.2. GET method ¶
We created a search.py file in the previous project to receive user requests:
/ HelloWorld/HelloWorld/search.py file code: ¶
fromdjango.httpimportHttpResponsefromdjango.shortcutsimportrender#
表单defsearch_form(request):returnrender(request,'search_form.html')#
接收请求数据defsearch(request):request.encoding='utf-8'if'q'inrequest.GETandrequest.GET['q']:message='你搜索的内容为:'+request.GET['q']else:message='你提交了空表单'returnHttpResponse(message)
Add the search_form.html form to the template directory templates:
/ HelloWorld/templates/search_form.html file code: ¶
菜鸟教程(runoob.com)
The urls.py rule is modified to the following form:
/ HelloWorld/HelloWorld/urls.py file code: ¶
fromdjango.conf.urlsimporturlfrom.importviews,testdb,searchurlpatterns=[url(r'^hello/$',views.runoob),url(r'^testdb/$',testdb.testdb),url(r'^search-form/$',search.search_form),url(r'^search/$',search.search),]
Access address http://127.0.0.1:8000/search-form/ And search, the results are as follows:
7.7.3. 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. Let’s use this method and use a URL and handler to display the view and process the request at the same time.
We create a post.html in templates:
/ HelloWorld/templates/post.html file code: ¶
菜鸟教程(runoob.com) {%
csrf_token
%}{{
rlt }}
At the end of the template, we add a rlt token to reserve a place for the table processing result.
There is a label at the end of the table for {% csrf_token%}. Csrf’s full name is Cross Site Request Forgery. This is a feature provided by Django to prevent masquerading requests from being submitted. The form submitted by the POST method 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
-*-fromdjango.shortcutsimportrenderfromdjango.views.decoratorsimportcsrf#
接收POST请求数据defsearch_post(request):ctx={}ifrequest.POST:ctx['rlt']=request.POST['q']returnrender(request,"post.html",ctx)
The urls.py rule is modified to the following form:
/ HelloWorld/HelloWorld/urls.py file code: ¶
fromdjango.conf.urlsimporturlfrom.importviews,testdb,search,search2urlpatterns=[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),]
Visit http://127.0.0.1:8000/search-post/ The display results are as follows:
After completing the above example, our directory structure is as follows:
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
7.7.4. Request object ¶
The first argument to each view function is a HttpRequest object, 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:
|
Attribute |
Description |
|---|---|
|
Path |
The full path to the request page, excluding the domain name-for example
|
|
Method |
A string representation of the HTTP method used in the request. All uppercase means. For example: if request.method == 'GET':
do_something()
elif request.method == 'POST':
do_something_else()
|
|
GET |
A class dictionary object that contains all HTTP GET parameters. See the QueryDict documentation. |
|
POST |
A class dictionary object that contains all HTTP POST parameters. See the QueryDict documentation.
It is also possible that the server receives an empty POST request. That is, the form form submits the request through the HTTP POST method, but there can be no data in the form. Therefore, you cannot use statements
Note: POST does not include
|
|
REQUEST |
For convenience, this attribute is a collection of POST and GET attributes, but with particularity, look for the POST attribute first, and then the GET attribute. Draw lessons from
For example, if
GET and POST is strongly recommended because these two attributes are more explicit and the written code is easier to understand. |
|
COOKIES |
A standard Python dictionary object that contains all cookies. Both Keys and values are strings. |
|
FILES |
Contains class dictionary objects for all uploaded files. Every Key in FILES is
Note: only if the request method is POST and < form > has
|
|
META |
A dictionary containing all available HTTP header information. For example:
These headers in META are prefixed.
|
|
User |
If the visiting user is not currently logged in, the user will be initialized to
You can tell whether a user is logged in or not through the is_authenticated () method of user: if request.user.is_authenticated():
# Do something for logged-in users.
else:
# Do something for anonymous users.
This property is available only when AuthenticationMiddleware in Django is activated |