Example of form processing in Python's Django framework

Source: Internet
Author: User
Create an example of a book, author, or publisher:

From django.db import Modelsclass Publisher (models. Model):  name = models. Charfield (max_length=30)  address = models. Charfield (max_length=50) City  = models. Charfield (max_length=60)  state_province = models. Charfield (max_length=30)  country = models. Charfield (max_length=50)  website = models. Urlfield () class Author (models. Model):  first_name = models. Charfield (max_length=30)  last_name = models. Charfield (max_length=40)  email = models. Emailfield () class book (Models. Model):  title = models. Charfield (max_length=100)  authors = models. Manytomanyfield (Author)  publisher = models. ForeignKey (Publisher)  publication_date = models. Datefield ()

Let's now create a simple view function so that users can find books from the database using the book title.
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:

From django.shortcuts import render_to_responsedef search_form (Request):  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:

  Search  

And the Urlpattern in urls.py may be this:

From mysite.books Import viewsurlpatterns = Patterns (",  # ...  (R ' ^search-form/$ ', views.search_form),  # ...)

(Note that we import the views module directly, rather than 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/search/that this form points to is not yet implemented. Let's add a second view function and set the URL:

# urls.pyurlpatterns = Patterns ("',  # ...  (R ' ^search-form/$ ', Views.search_form),  (R ' ^search/$ ', Views.search),  # ...) # Views.pydef Search (Request):  if ' Q ' in Request. GET:    message = ' searched for:%r '% request. get[' Q ']  else:    message = ' You submitted an empty form. '  return HttpResponse (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:

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").

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:

# bad!def Bad_search (Request):  # The following line would raise Keyerror if ' Q ' hasn ' t  # been submitted!  message = ' searched for:%r '% request. get[' Q ']  return httpresponse (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. We know that the request 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):

From django.http import httpresponsefrom django.shortcuts import render_to_responsefrom mysite.books.models Import Bookdef Search (Request):  if ' Q ' in Request. GET and request. get[' Q ']:    q = Request. get[' Q ']    books = Book.objects.filter (title__icontains=q)    return render_to_response (' search_results.html ',      {' Books ': Books, ' query ': q})  else:    return HttpResponse (' 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. (In real cases, we can use a custom query system with some sort of classification.) Search online for "open source full text search" To see if there is a good way to do it.

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:

{{Query}}

{% if books%}

Found {{books|length}} book{{books|pluralize}}.

    {% for book in books%}
  • {{Book.title}}
  • {% endfor%}
{% Else%}

No Books matched your search criteria.

{% ENDIF%}

Note the use of this pluralize, which will output s (e.g. find multiple books) when appropriate.

  • 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.