home PYTHONJAVA
 

Django form

HTML forms are the classic way of website interactivity. This chapter describes how to use Django to process user-submitted form data.


HTTP request

The HTTP protocol works in a "request-reply" manner. When a customer sends a request, they can append data to the request. By parsing the request, the server can obtain the data from the client and provide a specific service according to the URL.

GET method

We created a search.py file in our previous project to receive user requests:

/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') # Receiving request data def search(request): request.encoding='utf-8' if 'q' in request.GET: 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 to the template directory templates:

/HelloWorld/templates/search_form.html File code:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Programming tutorial welookups.com</title> </head> <body> <form action="/search" method="get"> <input type="text" name="q"> <input type="submit" value="search for"> </form> </body> </html>

Request object

The first argument to each view function is an HttpRequest object, like the hello() function below:

from django.http import HttpResponse< /span>

def hello(request):
     return HttpResponse ("Hello world")

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

Properties

Description

path

Request the full path to the page, excluding the domain name—for example, "/hello/".

method

A string representation of the HTTP method used in the request. All capitalized. 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 for the server to receive an empty POST request. That is, the form form submits the request via the HTTP POST method, but there is no data in the form. Therefore, you can't use the statement if request.POST to determine whether to use the HTTP POST method; you should use 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 property is a collection of POST and GET properties, but with speciality, look for the POST property first, then look for the GET property. Learn from PHP's $_REQUEST.

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

It is highly recommended to use GET and POST because these two properties are more explicit and the code being written is easier to understand.

COOKIES

A standard Python dictionary object that contains all cookies. Both Keys and values ​​are strings.

FILES

A class dictionary object that contains all uploaded files. Each Key in FILES is the value of the name attribute in the <input type="file" name="" /> tag. Each value in FILES is also a standard Python dictionary object, containing the following three Keys:

  • filename: Upload file name, represented by Python string
  • content-type: The content type of the uploaded file
  • content: The original content of the uploaded file

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

META

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

  • CONTENT_LENGTH
  • CONTENT_TYPE
  • QUERY_STRING: Unresolved raw 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 with HTTP_ most Key, for example:

  • HTTP_ACCEPT_ENCODING
  • HTTP_ACCEPT_LANGUAGE
  • HTTP_HOST: HTTP host header information sent by the client
  • HTTP_REFERER: referring page
  • HTTP_USER_AGENT: client-agent string for the client
  • HTTP_X_BENDER: X-Bender header information

user

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

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

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

if request.user.is_authenticated( ):
    # Do something for logged-in users.
else:
    # Do something for anonymous users.

This property is only available when you activate AuthenticationMiddleware in Django.

session

The only readable and writable property that represents the dictionary object for the current session. This property is only available when session support in Django is activated.

raw_post_data

The original HTTP POST data, not parsed. Useful for advanced processing.

The

Request object also has some useful methods:

methoddescription
__getitem__(key) Return the GET/POST key value, first take POST, then take GET. If the key does not exist, a KeyError is thrown.
This is where we can access the HttpRequest object using dictionary syntax.
For example, request["foo"] is equivalent to the first request.POST["foo"] and then request.GET["foo"].
Has_key() Check if request.GET or request.POST contains the Key specified by the parameter.
Get_full_path() Returns the request path containing the query string. For example, "/music/bands/the_beatles/?print=true"
Is_secure() If the request is safe, it returns True, that is, it is an HTTPS request.

QueryDict object

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

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

QueryDict implements all standard dictionary methods. Also includes some unique methods:

Method Description

__getitem__

is a little different from the standard dictionary, that is, if the Key corresponds to multiple Values, __getitem__() returns the last value.

__setitem__

Set the parameter to specify the key's value list (a Python list). Note: It can only be called on a mutable QueryDict object (that is, a copy of a QueryDict object generated by copy()).

get()

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

update()

The parameter can be either QueryDict or a standard dictionary. Unlike the update method of the standard dictionary, this method adds the 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()

A little different from the items() method of the standard dictionary, which uses __getitem__() with single-valued logic:

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

>>> q.items()

[('a', '3')]

values()

is a bit different from the values() method of the standard dictionary, which uses __getitem__() with single-valued logic:

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

Method Description

copy()

Returns a copy of the object. The internal implementation is copy.deepcopy() using the Python standard library. The copy is mutable (changeable) — that is, the value of the copy can be changed.

getlist(key)

returns all values ​​corresponding to the parameter key, returned 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_)

Set the value of the key to list_ (unlike __setitem__()).

appendlist(key,item)

Add items to the internal list associated with the key.

setlistdefault(key,list)

is a bit different from setdefault, which takes a list instead of a single value as a parameter.

lists()

is a little different from items(), which returns all 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 string formatted in the query string format (e.g., "a=2&b=3&b=5").






welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.