The Road to WeChat Mini Program Development (6) Django Form

The Road to WeChat Mini Program Development (6) Django Form

HTTP request
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 specific services based on the URL.
GET method
We created a search.py ​​file in the previous project to receive user requests:

from django.http import HttpResponse
from django.shortcuts import render
# 表单
def search_form(request):
    return render(request, 'search_form.html')
 
# 接收请求数据
def search(request):  
    request.encoding='utf-8'
    if 'cumt' in request.GET and request.GET['cumt']:
        message = '你搜索的内容为: ' + request.GET['cumt']
    else:
        message = '你提交了空表单'
    return HttpResponse(message)

Insert picture description here
Add the search_form.html form in the template directory templates:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>中国矿业大学信息安全</title>
</head>
<body>
    <form action="/search/" method="get">
        <input type="text" name="cumt">
        <input type="submit" value="搜索">
    </form>
</body>
</html>

Insert picture description here
The urls.py rules are modified as follows:

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),
]

Insert picture description here
Insert picture description here
Insert picture description here
POST method
Above we used the GET method. View display and request processing are divided into two function processing.
The POST method is more commonly used when submitting data. We use this method below, and use a URL and processing function to display the view and process the request at the same time.
We create post.html in templates:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>中国矿业大学计算机信息安全18-1班团支书</title>
</head>
<body>
    <form action="/search-post/" method="post">
        {% csrf_token %}
        <input type="text" name="cumt">
        <input type="submit" value="搜索">
    </form>
 
    <p>{
   
   { rlt }}</p>
</body>
</html>

Insert picture description here
At the end of the template, we add an rlt mark to reserve a place for the table processing results.
There is also a {% csrf_token %} label at the end of the form. The full name of csrf is Cross Site Request Forgery. This is a function provided by Django to prevent submitting requests in disguise. 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 POST requests:

from django.shortcuts import render
from django.views.decorators import csrf
 
# 接收POST请求数据
def search_post(request):
    ctx ={
    
    }
    if request.POST:
        ctx['rlt'] = request.POST['cumt']
    return render(request, "post.html", ctx)

Insert picture description here
The urls.py rules are modified as follows:

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),
]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Request object
The first parameter of each view function is an 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:

The full path of the requested page, not including the domain name—for example, "/hello/".

method

The string representation of the HTTP method used in the request. All uppercase representation. E.g:

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

GET
contains a dictionary-like object of all HTTP GET parameters. See the QueryDict documentation.
POST
contains a dictionary-like object of all HTTP POST parameters. See the QueryDict documentation.
It is also possible that the server receives an empty POST request. In other words, the form submits the request through the HTTP POST method, but there can be no data in the form. Therefore, you cannot 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 attribute in this table).
Note: POST does not include file-upload information. See FILES attribute.
REQUEST
For convenience, this attribute is a collection of POST and GET attributes, but it has particularities. First look for POST attributes and then GET attributes. Learn from PHP's $ REQUEST.
For example, if GET = {"name": "john"} and POST = {"age": '34'}, 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 the code written is easier to understand.
COOKIES
contains standard Python dictionary objects for all cookies. Both keys and values ​​are strings.
FILES
contains dictionary-like objects of all uploaded files. Each Key in FILES is the value of the name attribute in the tag. Each value in FILES is also a standard Python dictionary object, containing the following three Keys:
filename: The name of the uploaded file, expressed as a Python string
content-type: Content type of the
uploaded file content: The original content of the uploaded file
Note: Only when the request method is POST, and there is enctype="multipart/form-data" in the request page FILES only owns the data when it is an attribute. Otherwise, FILES is an empty dictionary.
META
contains a dictionary of 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 host name
SERVER_NAME: server host name
SERVER_PORT:
these headers in the server port META are prefixed with HTTP
as Key, followed by colon (:) Is Value, 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 user-agent string
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 as an instance of django.contrib.auth.models.AnonymousUser.
You can use the is_authenticated() method of user to identify whether the user is logged in:

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

Only in Django AuthenticationMiddleware property is available to activate the
session
unique writable attribute dictionary object representative of the current session. This attribute is only available when the session support in Django is activated.
raw_post_data
Raw HTTP POST data, unparsed. Useful for advanced processing.
The Request object also has some useful methods: the
method description
getitem (key) returns the key value of GET/POST, taking POST first, then 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 request.POST["foo"] and then request.GET["foo"].
has_key() Check whether the key specified by the parameter is included in request.GET or request.POST.
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 secure, it returns True, that is, it is an HTTPS request.
QueryDict object
In the HttpRequest object, the GET and POST attributes are instances of the django.http.QueryDict class.
QueryDict is a custom class similar to a dictionary, which is used to handle the situation where a single key corresponds to multiple values.
QueryDict implements all standard dictionary methods. It also includes some unique methods:
method description
getitem
and standard dictionary processing are a little different, that is, if Key corresponds to multiple Values, getitem () returns the last value.
The setitem
setting parameter specifies the value list of the key (a Python list). Note: It can only be called on a mutable QueryDict object (that is, a copy of a QueryDict object produced by copy()).
get()
If the key corresponds to multiple values, get() returns the last value.
The update()
parameter can be QueryDict or a standard dictionary. Unlike the standard dictionary update method, 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()

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

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

>>> q.items()

[('a', '3')]
values()

It is a little different from the values() method of the standard dictionary. This method uses __getitem__() of 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, and the internal implementation uses the Python standard The copy.deepcopy() of the library. The copy is mutable (changeable)—that is, the value of the copy can be changed.
getlist(key)
returns all the 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 item to the internal list associated with key.
setlistdefault(key,list )
Is a little different from setdefault in that it accepts a list instead of a single value as a parameter.
lists() is
a little different from items(), it will return all the values ​​of 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 (for example: "a=2&b=3&b=5").

Guess you like

Origin blog.csdn.net/xulei1132562/article/details/113585322