7.7. Django form

发布时间 :2025-10-25 12:24:13 UTC      

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:

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>菜鸟教程(runoob.com)</title></head><body><formaction="/search/"method="get"><inputtype="text"name="q"><inputtype="submit"value="搜索"></form></body></html>

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:

image0

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:

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>菜鸟教程(runoob.com)</title></head><body><formaction="/search_post/"method="post">{%
csrf_token
%}<inputtype="text"name="q"><inputtype="submit"value="搜索"></form><p>{{
rlt }}</p></body></html>

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:

image1

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 "/hello/" .

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 if request.POST To determine whether to use the HTTP POST method; you should use the if request.method == "POST" (see the method property of this table).

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

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 PHP's $_REQUEST .

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

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 <input type="file" name="" /> The value of the name attribute in the tag. Each value in FILES is also a standard Python dictionary object that contains the following three Keys:

  • Filename: upload file name, represented by Python string

  • Content-type: Content type for uploading files

  • Content: the original content of the uploaded file

Note: only if the request method is POST and < form > has enctype="multipart/form-data" The FILES owns the data only when the. Otherwise, FILES is an empty dictionary.

META

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

  • CONTENT_LENGTH

  • CONTENT_TYPE

  • QUERY_STRING: unparsed original query string

  • REMOTE_ADDR: client IP address

  • REMOTE_HOST: client hostname

  • SERVER_NAME: server hostname

  • SERVER_PORT: server port

These headers in META are prefixed. HTTP_ Is Key, followed by Value after the colon (:), for example:

  • HTTP_ACCEPT_ENCODING

  • HTTP_ACCEPT_LANGUAGE

  • HTTP_HOST: HTTP host header information sent by the customer

  • HTTP_REFERER: referring page

  • HTTP_USER_AGENT: client’s user-agent string

  • HTTP_X_BENDER: X-Bender header information

User

If the visiting user is not currently logged in, the user will be initialized to django.contrib.auth.models.AnonymousUser An example of.

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

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.