Home Backend Development Python Tutorial How to use django form form validation in Python

How to use django form form validation in Python

Mar 30, 2017 pm 05:20 PM

一. django formForm verification Introduction

Sometimes we need to use get, post, put, etc. to submit some data to the background processing example on the front-end HTML page;

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Form</title>
</head>
<body>
  <p>
    <form action="url" method="post" enctype="multipart/form-data">{% csrf_token %}
      <input type="text" name="username"/>
      <input type="password" name="password"/>
      <input type="submit" value="submit"/>
    </form>
  </p>
</body>
Copy after login

Front-end submission and background acquisition:

from django.shortcuts import render,HttpResponse,redirect
from app01 import models
def Login(request):
  if request.method == "POST":
    username = request.POST.get("username")
    password = request.POST.get("password")
    return HttpResponse("Hello,%s"%(username))
Copy after login


This completes the basic function and is basically ready to use.

However, if the user input does not follow the requirements (for example, the mobile phone number needs to enter 11 digits). length, password complexity, etc.), and the data that has been entered will be lost when you come back after submission.

Of course, if we manually obtain all the entered data in views and then pass it to the web page, This is feasible, but very inconvenient, so Django provides simpler and easier-to-use forms to solve a series of problems such as verification

. I have to mention that Django’s plug-in library is really powerful. Simple and easy to expand. The above content only introduces why form should be used. The following focuses on recording the use of django form

2. Form form verification application

It is necessary to create a new module form in the django APP. py, the specific content is as follows

class RegisterForm(forms.Form):
  email = forms.EmailField(required=True,
               error_messages={&#39;required&#39;: "邮箱不能为空"})
  password = forms.CharField(max_length=120,
                min_length=6,
                required=True,
                error_messages={&#39;required&#39;: "密码不能为空"})
  invite_code = forms.CharField(required=True,error_messages={&#39;required&#39;: "验证码不能为空"})
Copy after login

Front-end page

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>register</title>
</head>
<body>
  <p>
    <form action="url" method="post" enctype="multipart/form-data">
      <input type="text" name="username"/>
      <input type="password" name="password"/>
      <input type="text" name="code"/>
      <input type="submit" value="submit"/>
    </form>
  </p>
</body>
Copy after login

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(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")
Copy after login

Reg_Form(request.POST) Use the form class to process the submitted data to verify the legality of the data property, the logical processing after is_valid() is legal, the verified data is saved in the cleaned_data returned after instantiation,

cleaned_data is a dictionary data format, error information is saved in form. In errors, for example, if you want to view all error messages in viewsprint(f.errors), if you only want to see the user's error messages

 print(form.errors[&#39;username&#39;][0])
Copy after login

we can pass template renderingBack to the front-end page, example

<form action="/form/" method="POST">
{% csrf_token %}
    <p class="input-group">
      {#接收后台传过来的form对象,自动生成input标签#}
      {{ form.user }}
      {#从后台传过来的error是字典,直接{{ error.user.0 }}呈现错误信息#}
       {#如果后台返回了错误信息,将错误信息放入span标签,在页面显示,否则不显示#}
      {% 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="提交" />
    </p>
  </form>
Copy after login

3. Self-generated input box

Form class

class RegisterForm(forms.Form):
  style = &#39;form-control input-lg&#39;
  phone = forms.CharField(widget=forms.TextInput(attrs={&#39;class&#39;: style,
                              &#39;name&#39;: &#39;title&#39;})),
              required=True,
              error_messages={&#39;required&#39;: ugettext_lazy(&#39;*Required&#39;)})
  code = forms.CharField(widget=forms.NumberInput(attrs={&#39;placeholder&#39;: &#39;验证码&#39;,
                              &#39;class&#39;: style}),
              min_length=4,
              max_length=4,
              required=True,
              error_messages={&#39;required&#39;: ugettext_lazy(&#39;*Required&#39;)})
  password = forms.CharField(widget=forms.PasswordInput(attrs={&#39;placeholder&#39;: &#39;请输入密码&#39;,
                                 &#39;class&#39;: style}),
                min_length=6,
                required=True,
                error_messages={&#39;required&#39;: ugettext_lazy(&#39;*Required&#39;)})
Copy after login

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:
    # 如果不是post提交数据,就不传参数创建对象,并将对象返回给前台,直接生成input标签,内容为空
    f = Log_Form()
    return render(request, "login.html", {"form": f})
Copy after login

Front-end page

<body>
  <form action="/form/" method="POST">
  {% csrf_token %}
    <p class="input-group">
{#      接收后台传过来的form对象,自动生成input标签#}
      {{ form.user }}
{#      从后台传过来的error是字典,直接{{ error.user.0 }}呈现错误信息#}
{#      如果后台返回了错误信息,将错误信息放入span标签,在页面显示,否则不显示#}
    <p class="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="提交" />
    </p>
  </form>
</body>
</html>
Copy after login

IV. Form verification is perfect

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

The running order of form verification is init, clean, validate, save

clean and validate will be called successively in the form.is_valid() method

Exceptions encountered in clean and other steps: Exception Value: argument of type 'NoneType' is not iterable.

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

Don’t forget to return cleaned_data when rewriting the clean method

This rewriting can enable the data submitted by the user to be tested in the form class and return the data to the user. Logic will be performed after the data is legal. Processing, there is no need to process and return to the user, which is more convenient and reasonable

Additional:

5. Four initialization methods of form

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

②When defining a field, give the initial value oneformfield = forms.CharField(initial=value)

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

④When passing parameter instanse to form (i.e. oneform(instanse=onemodel_instance)), the first three initialization methods will all fail. Even when rewriting init, call it first The init of the parent class uses method ③ again, but it still doesn't work (not very cool).

If you want to reinitialize the field value at this time, you can only use self.initial['title'] = value in init(), and directly assign the value to the initial attribute dictionary of the Form class.

from django import forms
class RegisterForm(forms.Form):
  email = forms.EmailField(required=True,
               error_messages={&#39;required&#39;: "邮箱不能为空"})
  password = forms.CharField(max_length=120,
                min_length=6,
                required=True,
                error_messages={&#39;required&#39;: "密码不能为空"})
  invite_code = forms.CharField(required=True,error_messages={&#39;required&#39;: "验证码不能为空"})
  def clean(self):
    # 用户名
    try:
      email = self.cleaned_data['email']
    except Exception as e:
      raise forms.ValidationError(u"注册账号需为邮箱格式")
    # 验证邮箱
    user = User.objects.filter(username=email)
    if user: # 邮箱已经被注册了
      raise forms.ValidationError(u"邮箱已被注册")
    # 密码
    try:
      password = self.cleaned_data['password']
    except Exception as e:
      print('except: ' + str(e))
      raise forms.ValidationError(u"请输入至少6位密码")
    return self.cleaned_data
Copy after login

The above is the method of using django form form verification in Python introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. of. I would also like to thank you all for your support of the PHP Chinese website!

For more related articles on how to use django form form validation in Python, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles