Methods of using Django form forms validation in Python

Source: Internet
Author: User
I. http://www.php.cn/wiki/1515.html "target=" _blank ">django form validation introduced

Sometimes we need to use get,post,put and other methods in the foreground HTML page to submit some data to the background processing example;

<! DOCTYPE html>

Front-end Submission background acquisition:

From django.shortcuts import render,httpresponse,redirectfrom app01 import modelsdef Login (Request):  if Request.method = = "POST":    username = Request. Post.get ("username")    password = Request. Post.get ("password")    return HttpResponse ("hello,%s"% (username))


This completes the basic function, basically can use.

However, if the user input is not in accordance with the requirements (such as mobile phone number to lose data 11 bits length, the complexity of the password, etc.), there is the submission and then back to the input data will be gone

Of course, if we manually take the input after the data in the views to be transferred to the page, this is feasible, but very inconvenient, so Django provides more simple and easy to use forms to solve the series of problems such as validation

, we have to mention that Django's plugin library is really powerful, easy to expand, the above content is simply the introduction of why to use the form, the following focus on the use of Django form

Two. Form Validation application

You need to create a new module form.py in the Django app, as follows

Class Registerform (forms. Form):  email = forms. Emailfield (required=true,               error_messages={' Required ': "Mailbox cannot be Empty"})  password = forms. Charfield (max_length=120,                min_length=6,                required=true,                error_messages={' required ': "Password cannot be empty"})  Invite_code = forms. Charfield (required=true,error_messages={' required ': "Verification code cannot be empty"})

Front Page

<! DOCTYPE html>

Background views Processing

def register (Request):  if Request.method = = "POST":    f = reg_form (Request. POST)    if F.is_valid ():      user = f.cleaned_data["username"]      pwd = f.cleaned_data["password"]      code = f.cleaned_data["code"]      Res_code = request.session.get ("code", None)      result = models. UserInfo.objects.filter (userexact=user,pwdexact=pwd)      if code.upper () = = Res_code.upper () and result:        models . UserInfo.objects.filter (userexact=user). Update (Status=1)        request.session["User" = user        return redirect ("/Home")      Else:        return render (Request, "register.html", {"error": F.errors, "form": F}) Else:return render (Request, " Register.html ")

Reg_form (Request. Post) uses the form class to process the submitted data to verify the legitimacy of the data, Is_valid () the logical processing after it is valid, and the validated data is saved in the Cleaned_data returned after instantiation,

Cleaned_data is a dictionary data format, the error message is stored in the Form.errors for example to see all the error message print (f.errors), if only to see the user can

Print (form.errors[' username '][0])

Error message we can render back to the front page through a template, for example

<form action= "/form/" method= "POST" >{% csrf_token%}    <p class= "Input-group" >      {#接收后台传过来的form对象, Auto generate Input Label #}      {{Form.user}}      {#从后台传过来的error是字典, direct {{error.user.0}} render error message #} {#如果后台返回了错误信息, place error information into the span tag, on page Face display, otherwise do not show #}      {% if error.username.0%}      <span>{{error.userusername.0}}</span>      {% endif%}    </p>    <p class= "Input-group" >      {{Form.password}}      {% if error.pwd.0%}      <span >{{error.password. 0}}</span>      {% endif%}    </p>    <p>      <input type= "Submit "Value=" Submit "/>    </p>  </form>

Three. Self-generated input box

Form class

Class Registerform (forms. Form):  style = ' Form-control input-lg '  phone = forms. Charfield (widget=forms. TextInput (attrs={' class ': Style,                              ' name ': ' title '}),              required=true,              error_messages={' required ': Ugettext_lazy (' *required ')})  code = forms. Charfield (widget=forms. Numberinput (attrs={' placeholder ': ' Captcha ',                              ' class ': Style}),              min_length=4,              max_length=4,              required= True,              error_messages={' required ': Ugettext_lazy (' *required ')})  password = forms. Charfield (widget=forms. Passwordinput (attrs={' placeholder ': ' Please enter password ',                                 ' class ': Style}),                min_length=6,                required=true,                error_messages={' Required ': Ugettext_lazy (' *required ')})

Views

def register (Request):  if Request.method = = "POST":    f = registerform (Request. POST)    if F.is_valid ():      user = f.cleaned_data["username"]      pwd = f.cleaned_data["password"]      code = f.cleaned_data["code"]      Res_code = Request.session.get ("Checkcode", None)      result = models. UserInfo.objects.filter (userexact=user,pwdexact=pwd)      if code.upper () = = Res_code.upper () and result:        models . UserInfo.objects.filter (userexact=user). Update (Status=1)        request.session["User" = user        return redirect ("/Home")      Else:        return render (Request, "login.html", {"error": F.errors, "form": F})    else:      return render (Request , "login.html", {"error": F.errors, "form": F})  else: # If it is not a post-commit data, the object is created without arguments, and the object is returned to the foreground, and the input tag is generated directly, and the content is empty    f = Log_form ()    return render (Request, "login.html", {"Form": F})

Front Page

<body>  <form action= "/form/" method= "POST" > {% csrf_token%}    <p class= "Input-group" >{#      receives a Form object that is sent back from the background, automatically generates the input tag #}      {{Form.user}} {#      the error passed from the background is a dictionary, and the direct {{error.user.0}} renders a fault message #}{#      If the error message is returned in the background, the error message is placed in the span label, displayed on the page, otherwise the #} <p class is not displayed    = "Input-group" >      {{form.email}}      {% if error.email.0%}      <span>{{error.email.0}}</span>      {% endif%}    </p>     <p class= "Input-group" >      {{Form.password}}      {% if error.password.0%}      <span>{{error.password.0}}</span>      {% endif%}    </p>       < P class= "Input-group" >      {{form.code}}      {% if error.book_type.0%}      <span>{{error.code.0}}< /SPAN>      {% endif%}    </p>    <p>      <input type= "Submit" value= "submit"    /> </p >  </form></body>

Four. Form verification complete

docs.djangoproject.com/en/dev/ref/forms/validation/

The order in which form validation runs is Init,clean,validte,save

Where clean and validate are called successively in the Form.is_valid () method

Clean and other steps encountered an exception: Exception value:argument of type ' Nonetype ' is not iterable.

Maybe a field value in Cleaned_data should be a list, but it's actually a null value.

When you rewrite the Clean method, you must not forget the return Cleaned_data

This allows the user to submit data in the form class after the execution of the data returned to the user, the data is legitimate after the logical processing, no need to process the return user, more convenient and more reasonable

Add:

Four ways to initialize 5.form

① instantiation of Oneform (initial={' Onefield ': value})

② the initialization value Oneformfield = forms when the field is defined. Charfield (Initial=value)

③ rewrite the init () method of the form class: Self.fields[' Onefield '].initial = value

④ when you pass a parameter instanse (that is, Oneform (instanse=onemodel_instance)) to a form, the first three initialization methods are all invalidated, even if you override Init, calling the parent class's init and then using the method ③, is still invalid (not very cool).

In this case, the value of the initial property dictionary of the form class is assigned directly by initializing the field values only in init () self.initial[' title ' = value.

from Django Import Formsclass registerform (forms. Form): email = forms. Emailfield (required=true, error_messages={' Required ': "Mailbox cannot be Empty"}) Password = forms. Charfield (max_length=120, min_length=6, Required=true, error_messages={' Requi Red ': "Password cannot be empty"}) Invite_code = forms. Charfield (required=true,error_messages={' Required ': "Captcha cannot be Empty"}) def clean (self): # user Name try:email = Self.clean ed_data[' email '] except Exception as e:raise forms. ValidationError (U "registered account required for mailbox format") # Verify Mailbox user = User.objects.filter (username=email) If User: # Mailbox has been registered raise F Orms. ValidationError (U "Mailbox registered") # password Try:password = self.cleaned_data[' password '] except Exception as E:PR Int (' except: ' + str (e)) raise forms. ValidationError (U "Please enter at least 6 password") return Self.cleaned_data 

The above is a small part of the python to introduce the use of Django form forms validation method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for your support for topic.alibabacloud.com!

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.