search
HomeBackend DevelopmentPython TutorialHow to use django form form validation in Python

一. 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>

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


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;: "验证码不能为空"})

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>

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

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

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>

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

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

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>

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

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
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment