The Python framework's Django Learning notes (16)

Source: Internet
Author: User
Tags valid email address

Django Framework form (cont.)

Today is simply unable to spit groove, to the fragrant hills, the results and online to see is simply a difference ah, said the Xiangshan maple? What about the red leaves of Xiangshan? What's the red? This thought in the mountain, one breath climbed up, along the road is basically Green pine and cypress, cypress, ah pro, I am not only red green blind, or a pine maple not distinguish star people! More pit dad is back when, waiting for the bus waiting for nearly three hours, you say why not self-driving tour? No way, the poor can not afford to start Satan. In short, a sentence summed up the Fragrant Hills Tour:

If you hate him/her, let him/her go to Xiangshan on the weekend, if he/she loves you, let him/her take you to Xiangshan this weekend! Well, the chatter ends, although very tired, but learning or to continue to drip, and learning this need to adhere to, not a bit of perseverance, three days of fishing, two days, where can learn what things.

Form improvements

First, we made some minor improvements to the form on the basis of the last time, and the last search () view was very weak with the empty string-only one "please submit a search term" was displayed. Prompt for information. If the user wants to re-fill the form must click the "Back" button, this approach is both bad and unprofessional. If we write this in a real-world case, then Django's advantages will be lost.

A better solution when an empty string is detected is to re-display the form and give an error prompt on the form so that the user can immediately re-fill it. The simplest implementation method is to add the ELSE clause to re-display the form, with the following code:

1 From django.http import HttpResponse2 From django.shortcuts import render_to_response3 From books.models Import Book4 5 def search_form (request):6Return Render_to_response ('search_form.html')7 8 def search (request):9     if 'Q' inchRequest. GET and request. get['Q']:TenQ = Request. get['Q'] OneBooks = Book.objects.filter (title__icontains=q) AReturn Render_to_response ('search_results.html', -{'Books': Books,'Query': Q}) -     Else: the**return Render_to_response ('search_form.html', {'Error': True}) * *

PS: The Search_form () view is also included in order to view

In this code, we improved the search () View: Re-display search_form.html when the string is empty. and a variable error is passed to the template, which records the wrong message. Now let's edit the search_form.html to detect the variable error:

12<Head>3<title>Search</title>4</Head>5<body>6**{%ifError%}**7**<p style="color:red;">please Submit a search term.</p>**8**{% endif%}**9<form action="/search/"Method="Get">Ten<input type="text"Name="Q"> One<input type="Submit"Value="Search"> A</form> -</body> -

We modified the template used by the search_form () view because the Search_form () view did not pass the error variable, so the Search_form view in the bar does not display an error message.

With some of the above changes, the program is much better now, but now there is a question: is it necessary to write Search_form () specifically to display the form? As a practical practice, an empty form (with an error message) is displayed when a request is sent to/search/(data that does not contain a get). So, as soon as we change the search () View: Hides the error message when the user accesses/search/and does not commit any data, removing the search_form () view and the corresponding Urlpattern.

1 def search (request):2Error =False3     if 'Q' inchrequest. GET:4Q = Request. get['Q']5         ifNot Q:6Error =True7         Else:8Books = Book.objects.filter (title__icontains=q)9Return Render_to_response ('search_results.html',Ten{'Books': Books,'Query': Q}) OneReturn Render_to_response ('search_form.html', A{'Error': Error})

In the improved view, if the user accesses/search/and does not have get data, he will see a form with no error information, and if the user submits an empty form, it will see the error message and the form; Finally, if the user submits a non-empty value, he will see the search results.

Finally, let's refine the form a little bit and remove the redundant parts. Now that you have merged the two views with the URLs, the/search/view manages the display of the form and the display of the results, then there is no need to hardcode the specified URL for the action value of the form in the search_form.html. The original code is this:

1 <form action="/search/" method="get" >

Now change to this:

1 <form action= "" method="get">

Action= "means that the form will be submitted to the same URL as the current page. After this modification, if the search () view does not point to another page, you will no longer have to modify the action.

Simple validation

Our search examples are still fairly simple, especially in terms of data validation; We only verify that the search key value is empty. Many HTML forms then contain more complex validations than if the detection value is empty. We have seen error messages similar to the following on our website:

    • Please enter a valid email address, Foo ' is not a valid e-mail address.
    • Please enter a 5-digit U.S. ZIP code, 123 is not a valid ZIP code.
    • Please enter a date in YYYY-MM-DD format.
    • Please enter a password that is more than 8 digits and contains at least one number.

Let's adjust the search () view so that she can verify that the keyword is less than or equal to 20 characters. (To make the example more significant, we assume that if the keyword exceeds 20 characters it will cause the query to be very slow). So how do we do that? The simplest way is to embed the logical processing directly into the view, like this:

1 def search (request):2Error =False3     if 'Q' inchrequest. GET:4Q = Request. get['Q']5         ifNot Q:6Error =True7**elifLen (q) > -:**8**error = true**9         Else:TenBooks = Book.objects.filter (title__icontains=q) OneReturn Render_to_response ('search_results.html', A{'Books': Books,'Query': Q}) -Return Render_to_response ('search_form.html', -{'Error': Error})

Now, if you try to submit a search keyword that is more than 20 characters, the system does not perform a search operation, but instead displays an error message. However, the message in search_form.html is: "Please submit a search term.", which is obviously wrong, so we need more precise hints:

12<Head>3<title>Search</title>4</Head>5<body>6{%ifError%}7<p style="color:red;">please Submit a search term -Characters or shorter.</p>8{% ENDIF%}9<form action="/search/"Method="Get">Ten<input type="text"Name="Q"> One<input type="Submit"Value="Search"> A</form> -</body> -

But there are still some problems after the changes like this. It's easy to confuse us with the hint of Vientiane: Submit an empty form how does a hint about the 20 character limit appear? Therefore, the prompt information must be detailed, clear, will not produce a suspicion.

The essence of the problem is that we only use a Boolean variable to detect an error, rather than using a list to record the corresponding error message. We need to make the following adjustments:

1 def search (request):2**errors = []**3     if 'Q' inchrequest. GET:4Q = Request. get['Q']5         ifNot Q:6**errors.append ('Enter A search term.')**7         elifLen (q) > -:8**errors.append ('Please enter the most characters.')**9         Else:TenBooks = Book.objects.filter (title__icontains=q) OneReturn Render_to_response ('search_results.html', A{'Books': Books,'Query': Q}) -Return Render_to_response ('search_form.html', -{**'Errors': errors**})

Next, we want to modify the search_form.html template, now we need to display a errors list instead of a Boolean judgment.

12<Head>3<title>Search</title>4</Head>5<body>6**{%ifErrors%}**7**<ul>**8**{% forErrorinchErrors%}**9**<li>{{Error}}</li>**Ten**{% endfor%}** One**</ul>** A**{% endif%}** -<form action="/search/"Method="Get"> -<input type="text"Name="Q"> the<input type="Submit"Value="Search"> -</form> -</body> -

The Python framework's Django Learning notes (16)

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.