Implementation of automatic data verification for Django’s form component


1、 Form introduction

When we used the form table to submit data to the one-way back end in the HTML page before, we would write some tags to get the user’s input and wrap them with the form tag.

At the same time, we need to verify the user’s input in many scenarios, such as whether the user’s input, the length and format of the input are incorrect. If the user input content is wrong, it needs to display the corresponding error information in the corresponding position on the page.

The Django form component implements the functions described above.

In summary, the main functions of the form component are as follows:

  • Generate HTML tags available for the page
  • Verify the data submitted by users
  • Keep last input

2、 General handwritten registration function

def register(request):
  error_msg = ""
  if request.method == "POST":
    username = request.POST.get("name")
    pwd = request.POST.get("pwd")
    #Check the registration information
    if len(username) < 6:
      #The user length is less than 6 bits
      error_ MSG = "the length of user name cannot be less than 6 digits"
      #Save the user name and password to the database
      Return httpresponse ("registration successful")
  return render(request, "register.html", {"error_msg": error_msg})


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  < title > registration page
<form action="/reg/" method="post">
  {% csrf_token %}
    user name:
    <input type="text" name="name">
    <input type="password" name="pwd">
    < input type = submit "value = register" >
    <p style="color: red">{{ error_msg }}</p>

3、 Using form component to realize registration function

First, define a regform class

from django import forms

#Write a class according to the requirements of Django form component
class RegForm(forms.Form):
  name =  forms.CharField (label = user name)
  pwd =  forms.CharField (label = password)

Write another view function:

#Using form component to realize registration mode
def register2(request):
  form_obj = RegForm()
  if request.method == "POST":
    #When instantiating the form object, the data submitted by post is directly transferred in
    form_obj = RegForm(request.POST)
    #Call form_ The method of obj checking data
    if form_obj.is_valid():
      Return httpresponse ("registration successful")
  return render(request, "register2.html", {"form_obj": form_obj})


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  < title > registration 2 < / Title >
  <form action="/reg2/" method="post" novalidate autocomplete="off">
    {% csrf_token %}
      <label for="{{ }}">{{ }}</label>
      {{ }} {{ }}
      <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label>
      {{ form_obj.pwd }} {{ form_obj.pwd.errors.0 }}
      < input type = submit "value = register" >

Looking at the effect of the web page, we found that the function of the form is also verified

  • The front-end page is generated by the object of the form class — the function of generating HTML tags
  • When the user name and password are blank or wrong, the page will prompt the user to submit the verification function
  • When the user makes a mistake, the last input will be retained in the input box — > the last input will be retained

4、 Pychar’s exclusive test environment

1. Usage

1. Import the PY file to be tested

2. Generate an object

2. Some parameters of local verification test

from_ obj.is_ Valid() // judge whether the verification is passed
from_ obj.cleaned_ Data // get the current symbol check data {username ':'111','password ':'111'}
form_ obj.errors        //Get the data that does not pass the current verification

The parameter flag is used to transmit less and the parameter trun is used to transmit more. Because less data can't be checked, and more data can't be used. This is the form of a dictionary

5、 Three ways of generating input user input box automatically by HTML

The forms component only helps you render the tags that get user input (input selection drop-down file), but does not render buttons and form tags

Each input prompt rendered is capitalized in the field of the class

class MyRegForm(forms.Form):
  username =  forms.CharField (max_ length=8, min_ Length = 3) # the longest 8 bits, the shortest 3 bits
  password =  forms.CharField (max_ length=8, min_ Length = 3) # the longest 8 bits, the shortest 3 bits
  email =  forms.EmailField () mailbox verification
def reg(request):
  #Mr. 1 becomes an empty class object
  form_obj = MyRegForm()
  if request.method == 'POST':
    #3. Get user data and submit it to forms component for verification request.POST
    form_obj = MyRegForm(request.POST)
    #4. Get the verification results
    if form_obj.is_valid():
      Return httpresponse ('data OK ')
      #5. Get the fields and prompt information of verification failure
  #2 pass the object directly to the front page
  return render(request, 'reg.html', locals())

The first way is {{form}_ obj.as_ P} (not recommended)

Not recommended, high encapsulation and low scalability. General test for local use

<p>The first rendering method: multiple P tags are convenient for local testing, and the encapsulation degree is too high to be extended</p>
{{ form_obj.as_p }}
{#{{ form_obj.as_ul }}#}
{#{{ form_obj.as_table }}#}

The second way is {{} form_ obj.username }}(not recommended)

It is not recommended. It is highly extensible and cumbersome to write. Each input box needs to be written manually

<p>The second rendering method: high scalability, writing more cumbersome</p>
<label for="{{ form_obj.username.id_for_label }}">{{ form_obj.username.label }}</label>
{{ form_obj.username }}
{{ form_obj.password.label }}{{ form_obj.password }}
{{ }}{{ }}

The third way is for loop (recommended)

Recommended, for loop mode

* form.errors . 0} # this is template syntax

<p>The third rendering method is recommended</p>
<form action="" method="post" novalidate>
  {% for form in form_obj %}
    {{ form.label }}{{ form }}
    <span>{{ form.errors.0 }}</span>
  {% endfor %}
  <input type="submit">

6、 Data verification

*******There must be a front-end and back-end data verification, but the front-end verification is weak and dispensable

The back-end verification must be very comprehensive

How to cancel the browser’s automatic verification function?

Add the parameter no validate after the form and do not validate

Form form cancels the automatic verification function of front end browser 
  <form action="" method="post" novalidate>

Common calibration parameters

max_ Length / / maximum length allowed
min_ Length / / minimum length
Prompt information of label input, such as name, password, etc
error_ Messages customize the message of error reporting
‘max_ Length ‘: “the longest user name is 8 digits.”,
‘min_ Length ‘: “minimum 3 digits for user name”,
‘required ‘: “user name cannot be empty”
Required sets whether the field is allowed to be empty
Initial sets the default value
Widget control type and properties


Charfield user name type verification

from  django.forms  Import widgets // it's OK not to import, no prompt

class MyRegForm(forms.Form):
  #The minimum number of user names is 3 and the maximum number is 8
  username =  forms.CharField (max_ length=8,min_ Length = 3, label ='user name ',
                error_ Messages = {// prompt for error message
                  'max_ Length ': "the longest user name is 8 digits.",
                  'min_ Length ': "minimum 3 digits for user name",
                  'required ': "user name cannot be empty"
                }, required = false, initial ='jeff ', // null and default
                widget= forms.widgets.TextInput (attrs = {class':'form control C1 C2 '}), // set the type attribute of input to text and the class attribute

Password verification

class LoginForm(forms.Form):
  pwd = forms.CharField(
    Label = password,
    widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)

Mailbox type verification

class MyRegForm(forms.Form):
  #The email field must be filled with data in accordance with the mailbox format
  email =  forms.EmailField (label ='mailbox ', error)_ messages={
    'required ':'mailbox is required',
    'invalid':'mailbox format is incorrect '

Mobile phone number type verification

Regular matching

from django.core.validators import RegexValidator
class MyRegForm(forms.Form):
  #Mobile phone number
  phone = forms.CharField(
      Regexvalidator (R '^ [0-9] + $','Please enter a number '),  
      Regexvalidator (R '^ 159 [0-9] + $','number must start with 159 ')

Gender check

gender = forms.ChoiceField(
    Choices = ((1, "male"), (2, "female"), (3, "confidential"),
    Label = gender,

Hobby radio select Check

hobby = forms.ChoiceField(
    Choices = ((1, "Basketball"), (2, "football"), (3, "two color ball"),),
    Label = hobby,
    widget= forms.widgets.Select () single choice

Like multiple choice select check 1

hobby1 = forms.MultipleChoiceField(
    Choices = ((1, "Basketball"), (2, "football"), (3, "two color ball"),),
    Label = hobby,
    initial=[1, 3],

Like to check chekbox 2

hobby2 = forms.MultipleChoiceField(
    Choices = ((1, "Basketball"), (2, "football"), (3, "two color ball"),),
    Label = hobby,
    initial=[1, 3],

Remember password verification

keep = forms.ChoiceField(
    Label = "remember password or not",

7、 Hook function

#If you want to manipulate data in multiple fields at the same time, you use the global hook
#If you want to manipulate data in a single field, you use local hooks
Hook hook back after processing, but also back

Local hook

The verification user name cannot contain 666

#Local hook
#Here, self is my own class, myregform
  def clean_username(self):
    username = self.cleaned_data.get('username')
    if '666' in username:
      self.add_ Error ('user name ','Just calling 666 is not enough')
    return username

global hook

Two password verifications

class MyRegForm(forms.Form):
  password =  forms.CharField (max_ length=8,min_ Length = 3, label ='password ',
  Re_ password =  forms.CharField (max_ length=8,min_ Length = 3, label ='confirm password ',

  def clean(self):
    #Here, self is my own class, myregform
    #Check whether the password is consistent with the confirmation password
    password = self.cleaned_data.get('password')
    re_password = self.cleaned_data.get('confirm_password')
    if not password == re_password:
      #Display tips
      self.add_ error('re_ Password ','the two passwords are inconsistent')
      return self.cleaned_data

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress: recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]