Python's rookie path: Django form Validation

Source: Internet
Author: User
Tags html form html tags

Objective

There are two common ways to complete form validation in Django:

One is implemented via HTML + JS + Ajax.

The other is to use Django's own forms module to generate a corresponding HTML tag to complete the form validation. This is where this section is focused.

The first method: HTML + AJAX Implementation of the basic login page
<! DOCTYPE html>"en">"UTF-8"> <title></title> <style>. Error-msg{color:red; }    </style>"text"Name="User"/> </div> <div> <input type="Password"Name="pwd"/> </div> <div> <input type="text"Name="Num"/> </div> <div> <input type="text"Name="Phone"/> </div> <input type="Button"Value="Submit"onclick="dosubmit ();"/> </div> <script src="/static/jquery-2.1.4.min.js"></script> <script>function Dosubmit () {var input_dict= {}; $('input'). each (function () {var v=$ (this). Val (); var n= $ (this). attr ('name'); Input_dict[n]=v;            });            Console.log (input_dict); $('. Error-msg'). Remove (); $.ajax ({URL:'/login/', type:'POST', Data:input_dict, DataType:'JSON', success:function (result) {if(result.status) {location.href='/index/'; }Else{$.each (result.message, function (k,v) {Console.log (k,v[0].message                            ); <spanclass="error-msg"> Error Messages </span>var tag= Document.createelement ('span'); Tag.classname='error-msg'; Tag.innertext=V[0].message; Input[name="User"]                            $('input[name= "'+ K +'"]'). After (tag); })}}, Error:function () {}})} /c0></script></body>HTML code
 fromDjango.shortcutsImportRender,httpresponse#Create your views here. fromDjangoImportForms fromDjango.core.exceptionsImportValidationErrorImportRedefmobile_validate (value): Mobile_re= Re.compile (r'^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9]{8}$')    if  notMobile_re.match (value):RaiseValidationError ('cell phone number format error')classLoginForm (forms. Form): User= Forms. Charfield (Required=true, error_messages={'Required':'the user name cannot be empty.'}) PWD= Forms. Charfield (required=True, Min_length=6, Max_length=10, Error_messages={'Required':'The password cannot be empty.','Min_length':"at least 6 people"}) Num= Forms. Integerfield (error_messages={'Required':'The number cannot be empty.','Invalid':'You must enter a number'}) Phone= Forms. Charfield (validators=[Mobile_validate,],)ImportJSONdefLogin (Request):ifRequest.method = ='POST': Result= {'Status': False,'message': None} obj=LoginForm (Request. POST) ret=obj.is_valid ()ifret:Print(Obj.clean ()) result['Status'] =TrueElse:             fromDjango.forms.utilsImporterrordict#print (Type (obj.errors), Obj.errors.as_json ())Error_str =Obj.errors.as_json () result['message'] =json.loads (ERROR_STR)returnHttpResponse (Json.dumps (result))returnRender (Request,'login.html')
Views Code

Here, in the views, the Django comes with the forms module. Before we use this module, we need a bunch of if to judge the user input. If...if statement, but after using this module, only after defining the properties of each field in the LoginForm class, through obj = LoginForm (Request. POST) and ret = Obj.is_valid () Two steps, you can complete the validation of the user input information. RET returns whether the validation is all passed. True if one of the form information validation does not pass, false.

The knowledge that needs attention here is: Obj.clean () is the correct information to output the user post, is a dict,obj.errors is the output user post error message, is a UL Li display information, so inconvenient to view. Error messages can be presented in JSON form via Obj.errors.as_json () with error_str = Obj.errors.as_json () and result[' message ' = Json.loads (error_str ) to complete the error message collection.

When you define a form validation rule LoginForm class, the field name needs to be equal to the name value in the HTML

  Supplemental Knowledge points : In the defined loginform, the defined PWD field is defined like this

PWD = forms. Charfield (Required=true,                          min_length=6,                          max_length=10,                          error_messages={' required ': ' The password cannot be empty. ', ' Min_ Length ': "At least 6 bits"})

Where the Error_messages property is used to define the display of error messages. Interpreted as: If required authentication does not pass, the prompt ' password cannot be null ', min_length authentication does not pass, the error message is ' At least 6 bits '. Extension ' invalid ': ' must enter Number '

Second approach: Generate HTML tags with the forms module

The 2 problems that forms can solve:

Question 1: If the HTML comes with a form tag to commit, if the submitted data is wrong, it will clear all the data in the form, if the table items are more, very unfriendly to the user. Then the forms module will solve this problem.

Issue 2: Using the HTML form tag to submit the data, the name attribute of the input tag must be the same as the attribute of the class class defined. Instead of using the Django forms module, you don't need to consider this.

Python's rookie path: Django form Validation

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.