Python network programming 08 ---- Django form, python08 ---- django

Source: Internet
Author: User

Python network programming 08 ---- Django form, python08 ---- django

I. retrieving data from the Request object we have already introduced the HttpRequest object when talking about the View function, but we didn't talk much about it at the time. Let us recall that the first parameter of each view function is an HttpRequest object, just like the following hello () function:

from django.http import HttpResponsedef hello(request):    return HttpResponse("Hello world")

The HttpRequest object, such as the request variable in the above Code, has some interesting attributes and methods that you must familiarize yourself with so that you can know what you can do with them. During the execution of the view function, you can use these attributes to obtain information about the current request (for example, who is the user who is loading the page, or what browser is used ).

1. URL-related information

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

Attribute/Method Description Example
Request. path Request Path other than domain name, starting with a forward slash "/Hello /"
Request. get_host () Host Name (for example, domain name) "127.0.0.1: 8000" or "www.example.com"
Request. get_full_path () Request Path, which may contain query strings "/Hello /? Print = true"
Request. is_secure () If you use HTTPS for access, this method returns True; otherwise, False. True or False

In the view function, if you want to use a URL, always use this attribute or method to obtain the URL, instead of entering it manually. This makes the code more flexible for reuse elsewhere. The following is a simple example:

# BAD!def current_url_view_bad(request):    return HttpResponse("Welcome to the page at /current/")# GOODdef current_url_view_good(request):    return HttpResponse("Welcome to the page at %s" % request.path)

2. Submitted data information

In addition to basic metadata, The HttpRequest object has two attributes that contain the information submitted by the user: request. GET and request. POST. Both are dictionary-like objects. You can use them to access GET and POST data.

1. Class dictionary object

We say that request. GET and request. POST are dictionary-like objects. They act like Standard Dictionary objects in Python, but they are not standard dictionary objects at the underlying technical level. For example, both request. GET and request. POST have get (), keys (), and values () methods. You can use for key in request. GET to GET all the keys.

POST data is from HTML〈form〉Tag submitted, and GET data may come from〈form〉The submitted query string may also be the query string in the URL ).

A simple form processing example. Now we create a simple view function so that users can search for a blog from the database by name.


(Then do it, http://download.csdn.net/detail/a359680405/8401353)


Generally, form development is divided into two parts: the front-end HTML page user interface and the background view function to process the submitted data.

The first part is very simple. Now we create a view to display a search form:

from django.shortcuts import render_to_responsedef search_form(request):    return render_to_response('search_form.html')
Put it in blog \ views. py.

Search_form.html Template

The URLpattern in blog \ urls. py may be like this:

from django.conf.urls import patterns, include, urlurlpatterns = patterns('',    # ...    url(r'^search-form/$', 'blog.views.search_form'),    # ...)
Now, if you run the runserver command and then access http://127.0.0.1:8000/blog/search-form/, You will see the search interface. Very simple.

However, when you submit data through this form, you will get a Django 404 error. The URL/search/to which this Form points has not been implemented yet. Let's add the second view function and set the URL:

Blog \ urls. py

urlpatterns = patterns('',    # ...    url(r'^search-form/$', 'blog.views.search_form'),    url(r'^search/$', 'blog.views.search'),    # ...)
Blog \ views. py

def search(request):    if 'q' in request.GET:        message = 'You searched for: %r' % request.GET['q']    else:        message = 'You submitted an empty form.'    return HttpResponse(message)
In HTML, we define a variable q. When a form is submitted, the q value is appended to URL/search/through GET (method = "get. Request. GET is used to obtain the q value in the/search/(search () view.

It should be noted that q is included in request. GET. As mentioned in the request. META section above, data submitted by users and even correct data must be filtered. If no detection is performed here, submitting an empty form will cause a KeyError exception:

2. query string Parameters

The data obtained using the POST method is similar to the GET method, but request. POST is used instead of request. GET. So what is the difference between POST and GET? You can use GET when submitting a form to retrieve data. When submitting a form, you must change the server data status or send an email, or, when you obtain and display dataUse POST. In this blog search example, we use GET because this query does not change the server data status. (If you are interested in

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.