Simple parsing of form validation in the Django framework

Source: Internet
Author: User
Tags valid email address
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.

About JavaScript validation

You can use JavaScript to validate data in the client browser, which is beyond the scope of this book. Note: The server side must be validated again even if the client has already verified it. Because some users will shut down JavaScript, and some malicious users will try to commit illegal data to detect whether there is an opportunity to attack.

In addition to validating user-submitted data on the server side (for example, validating in a view), there is no other way. JavaScript validation can be seen as an additional feature, but not as a unique validation feature.

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:

def search (Request):  error = False  if ' Q ' in Request. GET:    q = Request. get[' Q ']    if not Q:      error = True    **elif len (q) > 20:**      **error = true**    Else:      books = Book.obje Cts.filter (title__icontains=q)      return render_to_response (' search_results.html ',        {' 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:

  Search  {% if error%}    

Please submit a search term of characters or shorter.

{% ENDIF%}

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:

def search (Request):  **errors = []**  if ' Q ' in Request. GET:    q = Request. get[' Q ']    if not Q:      **errors.append (' Enter a search term. ') * *    elif len (q) >:      **errors.append (' Please enter at the most characters. ') * *    Else:      books = Book.objects.filter (title__icontains=q)      return render_to_response (' Search_ Results.html ',        {' 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.

  Search  **{% If Errors%}** * *
 
  
  
    * **{% for error in errors%}** * *
  • {{Error}}
  • * * **{% endfor %}** *
* * * **{% endif%}**
  • 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.