Python uses the django form verification method, pythondjango

Source: Internet
Author: User

Python uses the django form verification method, pythondjango

1. Introduction of django form Verification 

Sometimes we need to use get, post, put, and other methods to submit some data to the backend for processing on the front-end HTML page;

<!DOCTYPE html>

Frontend submission for background retrieval:

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))

In this way, the basic functions are completed and can be basically used.

However, if the user input is not in accordance with the requirements (such as the 11-bit length of the data to be input by the mobile phone number, the complexity of the password, and so on), there will be no input data returned after submission.

Of course, if we manually obtain the input data in views and then pass it to the webpage, this is feasible, but it is inconvenient, therefore, Django provides easier-to-use forms to solve verification and other problems.

Here, I have to mention that the Django plug-in library is really powerful and easy to expand. The above content only introduces why form is used. The following focuses on recording the usage of django form.

Ii. form Verification Application

Create a new form. py module in the django APP. The details are as follows:

Class RegisterForm (forms. form): email = forms. emailField (required = True, error_messages = {'requestred': "email cannot be blank"}) password = forms. charField (max_length = 120, min_length = 6, required = True, error_messages = {'required': "The password cannot be blank"}) invite_code = forms. charField (required = True, error_messages = {'required': "The Verification Code cannot be blank "})

Front-end page

<!DOCTYPE html>

Backend 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(user__exact=user,pwd__exact=pwd)      if code.upper() == res_code.upper() and result:        models.UserInfo.objects.filter(user__exact=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) The form class is used to process submitted data to verify the validity of the data. The is_valid () is valid for logical processing, and the verified data is stored in the cleaned_data returned after instantiation,

Cleaned_data is a dictionary data format. The error information is stored in form. errors. For example, if you want to view all the error messages in views, print (f. errors ).

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

The error message can be rendered back to the front-end page through a template, for example

<Form action = "/form/" method = "POST" >{% csrf_token %} <div class = "input-group" >{# receive form objects transmitted from the background, automatically generate input tag #} {form. user }}{# the error passed from the background is a dictionary and {error. user.0 }}error message # }{# if an error message is returned in the background, add the error message to the span tag and display it on the page. Otherwise, the error message is not displayed. # }{% if error. username.0 %} <span >{{ error. userusername.0 }}</span >{% endif % }</div> <div class = "input-group" >{{ form. password }}{% if error. pwd.0 %} <span >{{ error. password. 0 }}</span >{% endif % }</div> <input type = "submit" value = "submit"/> </div> </form>

Iii. 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 = {'holder': '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 ': 'Enter the 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 (user _ exact = user, pwd _ exact = pwd) if code. upper () = res_code.upper () and result: models. userInfo. objects. filter (user _ exact = 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 data is not submitted by post, the parameter will not be passed to create the object, and the object will be returned to the foreground, directly generating the input tag, blank content f = Log_Form () return render (request, "login.html", {"form": f })

Front-end page

<Body> <form action = "/form/" method = "POST" >{% csrf_token %} <div class = "input-group" >{# receives form object, automatically generate input tag #} {form. user }}{# the error passed from the background is a dictionary and {error. user.0 }}error message # }{# if an error message is returned in the background, add the error message to the span tag, which is displayed on the page, otherwise it is not displayed #} <div class = "input-group"> {form. email }}{% if error. email.0 %} <span >{{ error. email.0 }}</span >{% endif %}</div> <div class = "input-group" >{{ form. password }}{% if error. password.0 %} <span >{{ error. password.0 }}</span >{% endif %}</div> <div class = "input-group" >{{ form. code }}{% if error. book_type.0 %} <span >{{ error. code.0 }}</span >{% endif % }</div> <input type = "submit" value = "submit"/> </div> </form> </body> 

Iv. Complete Form Verification

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

The running sequence of form Verification is init, clean, validte, save

The clean and validate methods are called successively in the form. is_valid () method.

Exception encountered in steps such as clean: Exception Value: argument of type 'nonetype 'is not iterable.

It may be that the value of a field in cleaned_data should be a list, but it is actually a null value.

Do not forget return cleaned_data when the clean method is rewritten.

In this way, the data submitted by the user can be returned to the user after the detection is completed in the form class. After the data is valid, the data is processed logically without being processed and returned to the user, making it more convenient and reasonable.

Supplement:

5. Four form initialization Methods

① Instantiate oneform (initial = {'onefield ': value })

② Initialize the field value oneformfield = forms. CharField (initial = value)

③ Override the _ init _ () method of the Form class: self. fields ['onefield']. initial = value

④ When the parameter instanse (oneform (instanse = onemodel_instance) is passed to form, all the first three initialization methods will fail, even if _ init _ is rewritten, the _ init _ of the parent class is called first and then the method ③ is used. It is still invalid (not very nice ).

In this case, you can only re-initialize the field value in self. initial ['title'] = value in _ init _ (), and assign a value to the initial attribute Dictionary of the Form class.

From django import formsclass RegisterForm (forms. form): email = forms. emailField (required = True, error_messages = {'requestred': "email cannot be blank"}) password = forms. charField (max_length = 120, min_length = 6, required = True, error_messages = {'required': "The password cannot be blank"}) invite_code = forms. charField (required = True, error_messages = {'requestred': "The Verification Code cannot be blank"}) def clean (self): # username try: email = self. cleaned_data ['email '] failed t Exception as e: raise forms. validationError (u "the registered account must be in the email format") # verify the email user = User. objects. filter (username = email) if user: # the email address has been registered with raise forms. validationError (u "email already registered") # password try: password = self. cleaned_data ['Password'] cipher t Exception as e: print ('cipher T: '+ str (e) raise forms. validationError (u "Enter at least six passwords") return self. cleaned_data

The above section describes how to use django form Verification in Python. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.