Home  >  Article  >  Backend Development  >  How to use django form form validation in Python

How to use django form form validation in Python

高洛峰
高洛峰Original
2017-03-30 17:20:432062browse

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