Python - Django - form custom validation component

reg2.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="/reg2/" method="post" novalidate>
                {% csrf_token %}
                <div class="form-group {% if form_obj.username.errors.0 %}has-error{% endif %}">
                    {{ form_obj.username.label }}
                    {{ form_obj.username }}
                    <span class="help-block">{{ form_obj.username.errors.0 }}</span>
                </div>
                <div class="form-group {% if form_obj.password.errors.0 %}has-error{% endif %}">
                    {{ form_obj.password.label }}
                    {{ form_obj.password }}
                    <span class="help-block">{{ form_obj.password.errors.0 }}</span>
                </div>
                <div class="form-group {% if form_obj.re_password.errors.0 %}has-error{% endif %}">
                    {{ form_obj.re_password.label }}
                    {{ form_obj.re_password }}
                    <span class="help-block">{{ form_obj.re_password.errors.0 }}</span>
                </div>
                <div class="form-group {% if form_obj.mobile.errors.0 %}has-error{% endif %}">
                    {{ form_obj.mobile.label }}
                    {{ form_obj.mobile }}
                    <span class="help-block">{{ form_obj.mobile.errors.0 }}</span>
                </div>
                <p><input type="submit" class="btn btn-default"></p>
            </form>
        </div>
    </div>
</div>

</body>
</html>

View forms.py source

 

If there is a function that begins clean_, while the back is cleaned_data name with the key, the function will be executed

views.py:

from django.shortcuts import render, HttpResponse
from app01 import models

from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegForm(forms.Form):
    username = forms.CharField(
        min_length=5,
        label="用户名",
        error_messages={
            "min_length": "用户名不能小于5位!",
            "required": "该字段不能为空"
        },
        widget=widgets.TextInput(attrs={"class": "form-control"})
    )

    password = forms.CharField(
        min_length=6,
        label = "password"
        = {error_messages, 
            "min_length": "not less than 6 Password!", 
            "required": "This field can not be blank" 
        }, 
        the widget = widgets.PasswordInput (attrs = { "class": "form-Control"}, = True render_value) 
    ) 

    re_password = forms.CharField ( 
        min_length =. 6, 
        label = "confirm password", 
        error_messages, = { 
            "required": "this field can not be blank" 
        }, 
        the widget = widgets.PasswordInput (attrs = { "class" : "form-Control"}, render_value = True) 
    ) 

    Mobile = forms.CharField ( 
        label = "phone number"
        Custom # regular matching rules 
        validators = [ 
            RegexValidator (R & lt '^ [0-9] + $', 'phone number must be a number "), # determines whether or not a digital mobile phone number
            RegexValidator (r '^ 1 [3-9 ] [0-9] {9} $', " Mobile phone format error") determines whether the phone number is # 1 and beginning eleven bits 3-9 
            # If by check 
        ],
        = {error_messages, 
            "required": "This field can not be blank", 
        }, 
        the widget = widgets.TextInput (attrs = { "class": "form-Control"}) 
    ) 

    # determines the user name information 
    DEF clean_username (Self): 
        value self.cleaned_data.get = ( "username") 
        IF "ADMIN" in value: 
            The raise ValidationError ( "user name can not contain sensitive information") 


DEF reg2 (request): 
    form_obj regform = () # GET request 

    if request.method == "POST": 
        form_obj = regform (request.POST) 
        # let form to help us verify 
        IF form_obj.is_valid (): 
            # after all data are kept in check form_obj.cleaned_data
            print(form_obj.cleaned_data) 
            models.UserInfo.objects.create (** form_obj.cleaned_data) 
            return HttpResponse ( "Registration Success") 

    return the render (Request, "reg2.html", { "form_obj" : form_obj})

Clean_username add a function to form a class determination processing username

operation result:

 

 

Override clean parent class method:

View forms.py of source

 

Here clean method only returned cleaned_data in the last time, in the middle there is no operation

views.py:

from django.shortcuts import render, HttpResponse
from app01 import models

from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegForm(forms.Form):
    username = forms.CharField(
        min_length=5,
        label="用户名",
        error_messages={
            "min_length": "用户名不能小于5位!",
            "required": "该字段不能为空"
        },
        widget=widgets.TextInput(attrs={"class": "form-control"})
    )

    password = forms.CharField(
        min_length=6,
        label = "password"
        = {error_messages, 
            "min_length": "not less than 6 Password!", 
            "required": "This field can not be blank" 
        }, 
        the widget = widgets.PasswordInput (attrs = { "class": "form-Control"}, = True render_value) 
    ) 

    re_password = forms.CharField ( 
        min_length =. 6, 
        label = "confirm password", 
        error_messages, = { 
            "required": "this field can not be blank" 
        }, 
        the widget = widgets.PasswordInput (attrs = { "class" : "form-Control"}, render_value = True) 
    ) 

    Mobile = forms.CharField ( 
        label = "phone number"
        Custom # regular matching rules 
        validators = [ 
            RegexValidator (R & lt '^ [0-9] + $', 'phone number must be a number "), # determines whether or not a digital mobile phone number
            RegexValidator (r '^ 1 [3-9 ] [0-9] {9} $', " Mobile phone format error") determines whether the phone number is # 1 and beginning eleven bits 3-9  
        ],
        error_messages, = { 
            " required ":" this field can not be blank ", 
        }, 
        the widget = widgets.TextInput (attrs = {" class ":" form-Control "}) 
    ) 

    # determines the user name information 
    DEF clean_username (Self): 
        value = self.cleaned_data .get ( "username") 
        IF "ADMIN" in value: 
            the raise the ValidationError ( "user name can not contain sensitive information") 

    # override the parent class clean 
    DEF clean (Self): 
        password = self.cleaned_data.get ( "password ") 
        re_password = self.cleaned_data.get (" re_password ")
        if re_password != password:
            self.add_error ( "password", ValidationError ( " password twice inconsistent"))  
            self.add_error ( "re_password ", ValidationError (" password twice inconsistent "))
            The raise ValidationError ( "password twice inconsistent") 
        return self.cleaned_data 


DEF reg2 (Request): 
    form_obj regform = () # GET request 

    if request.method == "POST": 
        form_obj = regform (request.POST) 
        # let form to help us verify 
        IF form_obj.is_valid (): 
            # If by check 
            form_obj.cleaned_data # after all data are kept in check 
            print ( form_obj.cleaned_data) 
            models.UserInfo.objects.create (** form_obj.cleaned_data) 
            return the HttpResponse ( "registration is successful") 

    return the render (Request, "reg2.html", { "form_obj": form_obj})

Reconstruction method of the parent class in clean form classes, to verify the password part

If the two passwords are different, the results:

 

Guess you like

Origin www.cnblogs.com/sch01ar/p/11498962.html