Django practice (9): Implements product Input Validation

Source: Internet
Author: User

Let's complete the task in the previous section:

1. Verify price> 0: It must be verified in form;
2. unique title verification: verification in model;
3. Verify the image_url Extension: Verify it in form, and change it to the urlfield type in model by the way.

The property cannot be empty in the previously generated scaffold:

However, the uniqueness of the URL format, the suffix of rul, and title is not verified. First, add the URL format and title uniqueness check in the model:

 

 
FromDjango. DBImportModelsClassProduct (models. Model): Title= Models. charfield (max_length = 100, unique =True) Description=Models. textfield () image_url= Models. urlfield (max_length = 200)) Price= Models. decimalfield (max_digits = 8, decimal_places = 2)

 

Add unique = true on the title and change the image_url type to urlfield:

 

The remaining image format suffix, price> 0 verification needs to be implemented in form:

Depot/depotapp/forms. py

 #  /Usr/bin/Python  #  Coding: utf8  From Django Import  Forms  From Models Import * Import  Itertools  Def Anytrue (predicate, sequence ):  Return True In  Itertools. IMAP (predicate, sequence)  Def Endswith (S ,* Endings ):  Return  Anytrue (S. endswith, endings)  Class  Productform (forms. modelform ):  Class  Meta: Model = Product  Def  _ Init __ (Self, * ARGs ,** Kwargs): Super (productform, self ).  _ Init __ (* ARGs ,** Kwargs)  Def  Clean_price (Self): Price = Self. cleaned_data [ '  Price  '  ]  If Price <= 0:  Raise Forms. validationerror ("  Price must be greater than zero  "  )  Return  Price  Def  Clean_image_url (Self): URL = Self. cleaned_data [ '  Image_url  '  ]  If   Not Endswith (URL, '  . Jpg ' , '  . PNG  ' , '  . Gif  '  ):  Raise Forms. validationerror ( '  The image format must be JPG, PNG, or GIF.  '  )  Return  URL 

Productform is inherited from modelform and can be automatically generated based on model attributes.

 

Added clean_price and clean_image_url verification on the generated productform. The result is as follows:

How are forms displayed? Take a look at the template:

Depot/depotapp/templates/depotapp/create_product.html

 

 {% Extends "base.html" % }{% block title %} create a product {% endblock % }{% block content %}  <  Table  >  <  Form  Action  = ""  Method  = "Post"  > {% Csrf_token %} {form }}  <  Tr  >      <  TD  Colspan  = "2"  Align  = "Right"  > <  Input  Type  = "Submit"  Value  = "CREATE"  /> </ TD  >    </  Tr  >  </  Form  >  </  Table  >  {% Endblock %} 

 

Directly output the form object ({fom} Will format the form into a form (table is used by default, or <p> or <li> can be specified through as_p and as_ul ), and contains the error message.

 

{% Csrf_token %} is used to add a token form item,Avoid repeated submissionPrevents cross-site forgery requests.

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.