The Python framework's Django Learning notes (15)

Source: Internet
Author: User

Form

From Google's simple single search box, to the Common Blog review submission form, to the complex custom data entry interface, HTML forms have always been the backbone of interactive sites. This article will show you how to use Django to access the data submitted by the user through the form, validation checks, and other processing. At the same time, we will introduce the HttpRequest object and the Form object.

Getting data from the request object

The HttpRequest object has been introduced in the previous function of the view, but not much at the time. Let's recall that the first parameter of each view function is a HttpRequest object, just like this hello () function:

1  from Import HttpResponse 2 3 def Hello (Request): 4     return HttpResponse ("HelloWorld")

HttpRequest objects, such as the request variables in the code above, are interesting and you have to familiarize yourself with these properties and methods to know what to do with them. During the execution of the view function, you can use these properties to get some information about the current request (for example, who you are loading the page from, or what browser you are using).

URL-related Information

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

In the view function, always use this property or method to get the URL instead of entering it manually. This makes the code more flexible so that it can be reused elsewhere. The following is a simple example:

1 #bad!2 defCurrent_url_view_bad (Request):3     returnHttpResponse ("Welcome to the page at/current/")4 5 #Good6 defCurrent_url_view_good (Request):7     returnHttpResponse ("Welcome to the page at%s"% Request.path)

Submitted Data information

In addition to the basic metadata, the HttpRequest object has two properties that contain the information submitted by the User: request. GET and request. POST. Both are class Dictionary objects that you can use to access get and post data.

Class Dictionary Object

We say "request." Get and Request.post are class dictionary objects, meaning they behave like standard dictionary objects in Python, but they are not standard dictionary objects at the bottom of the technology. For example, request. Both get and request.post have get (), keys (), and the values () method, which you can use for key in request. Get gets all the keys.

What difference does it have? Because of the request. Get and Request.post have some methods that are not common to dictionary objects. We'll talk about it later.

You may have encountered similar names before: Class file objects, which have some basic methods, such as read (), to make a substitute for a real Python file object.

The post data is submitted from the 〈form〉 tag in the HTML, and the get data may be from the 〈form〉 commit or the query string in the URL (the "query string").

A simple example of form processing

Typically, 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 let's create a view to display a search form:

1  from Import Render_to_response 2 3 def Search_form (Request): 4     return render_to_response ('search_form.html')

This view function can be placed anywhere in the Python search path. For the sake of discussion, let's put it in the books/views.py.

This search_form.html template may look like this:

123<title>Search</title>45<body>6<form action="/search/"Method="Get">7<input type="text"Name="Q">8<input type="Submit"Value="Search">9</form>Ten</body> One

And the Urlpattern in urls.py may be this:

1  from Import  views 2 3 urlpatterns = Patterns ("',4     #  ... 5     (R'^search-form/$', views.search_form), 6     #  ... 7 )

PS: We import the views module directly, instead of using a statement like from Mysite.views import Search_form, because the former looks more concise.

Now, if you run the runserver command and then access http://127.0.0.1:8000/search-form/, you'll see the search interface. Very simple.

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

1 #urls.py2 3Urlpatterns = Patterns ("',4     # ...5(r'^search-form/$', Views.search_form),6(r'^search/$', Views.search),7     # ...8 )9 Ten #views.py One  A defSearch (Request): -     if 'Q' inchrequest. GET: -Message ='You searched for:%r'% request. get['Q'] the     Else: -Message ='You submitted an empty form.' -     returnHttpResponse (Message)

Temporarily display only the words the user searched to make sure that the search data is correctly submitted to Django, so you know how the search data is passed through the system. Nutshell:

    1. In HTML we define a variable Q. When the form is submitted, the value of the variable q is appended to the url/search/by get (method= "get").
    2. The view that handles/search/(search ()) is passed request. Get to get the value of Q.

It is important to note here that Q is explicitly included in the request. Get in. Just like the request above. The meta section mentions that filtering is required for the data submitted by the user, even the correct data. If there is no detection, then the user submits an empty form that throws a Keyerror exception:

1 #bad!2 defBad_search (Request):3     #The following line would raise keyerror if ' Q ' hasn ' t4     #been submitted!5Message ='You searched for:%r'% request. get['Q']6     returnHttpResponse (Message)

Query string parameters

Because the data using the Get method is passed through the query string (for example,/search/?q=django), we can use Requet. Get to get the data. Before introducing Django's urlconf system, we compared Django's concise URL with the Php/java traditional URL, which we know can be used in the view. Get to get the query string in the traditional URL (for example, hours=3).

Getting the data using the Post method is similar to get, just using request. Post instead of Request.get. So what's the difference between post and get? When we submit a form, we can use get when we just need to get the data, and when we submit the form we need to change the state of the server data, or send an e-mail, or other than just get and display the data to use post. In this example of a search book, we use GET, because this query does not change the state of the server data. (If you are interested in learning more about get and POST , refer to http://www.w3.org/2001/tag/doc/whenToUseGet.html.) )

Now that you have verified that the data submitted by the user is valid, you can then query the database for this valid data (again, in views.py):

1  fromDjango.httpImportHttpResponse2  fromDjango.shortcutsImportRender_to_response3  fromMysite.books.modelsImport Book4 5 defSearch (Request):6     if 'Q' inchRequest. GET andRequest. get['Q']:7Q = Request. get['Q']8Books = Book.objects.filter (title__icontains=q)9         returnRender_to_response ('search_results.html',Ten{'Books': Books,'Query': Q}) One     Else: A         returnHttpResponse ('Please submit a search term.')

Let's examine the code above:

    • In addition to checking if q exists in request. Get outside, we also check to Reuqest. Whether the value of get[' Q '] is empty.
    • We use Book.objects.filter (title__icontains=q) to get the books in the database with Q in the title. Icontains is a query keyword. This statement can be understood to get a book containing Q in the title, not case sensitive.
    • This is a very simple way to implement a book query. We do not recommend using Icontains queries in a database that contains a large number of products, because that can be slow.
    • Finally, we pass the template to books, a list that contains the book object. The display template for the query results is search_results.html as follows:
1<p>you searched for: <strong>{{Query}}</strong></p>2 3{%ifBooks%}4<p>found {{books|length}} book{{books|pluralize}}.</p>5<ul>6{% forBookinchBooks%}7<li>{{Book.title}}</li>8{% ENDFOR%}9</ul>Ten{%Else%} One<p>no Books matched your search criteria.</p> A{% ENDIF%}

Note the use of pluralize here, the filter will output s when appropriate.

The above is the content of this study ~

The Python framework's Django Learning notes (15)

Related Article

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.