form表单的密码是否一致校验功能

这是form类表单,自定义的form表单,需要重写钩子函数

"""
forms类表单
"""
# 校验密码是否一致
from django.core.exceptions import ValidationError

from django import forms


class RegForm(forms.Form):
    username = forms.CharField(
        max_length=16,
        label=‘用户名‘,
        label_suffix=":",   # 后缀
        error_messages={
            "max_length": "用户名最长16位",
            "required": "用户名不能为空"
        },
        widget=forms.widgets.TextInput(
            attrs={
                "class": "form-control"
            }
        )
    )

    password = forms.CharField(
        min_length=6,
        label=‘密码‘,
        widget=forms.widgets.PasswordInput(
            attrs={
                "class": "form-control"
            },
            render_value=True,      #提交数据不把密码清空
        ),
        error_messages={
            "min_length": "密码至少六位数",
            "required": "密码不能为空"
        }
    )

    re_password = forms.CharField(
        min_length=6,
        label=‘确认密码‘,
        widget=forms.widgets.PasswordInput(
            attrs={
                "class": "form-control"
            }
        ),
        error_messages={
            "min_length": "密码至少六位数",
            "required": "密码不能为空"
        }
    )

    email = forms.EmailField(
        label=‘邮箱‘,
        widget=forms.widgets.EmailInput(
            attrs={
                "class": "form-control"
            }
        ),
        error_messages={
            "invalid": "邮箱格式不正确!",
        }
    )

    # 重写全局的钩子函数,对确认密码做校验
    def clean(self):
        password = self.cleaned_data.get("password")
        re_password = self.cleaned_data.get("re_password")

        if re_password and re_password != password:
            self.add_error("re_password",ValidationError("两次密码不一致"))
        else:
            return self.cleaned_data

  在HTML里面应该这样写

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <title>欢迎注册</title>
    <link rel="stylesheet" href="{% static ‘bootstrap/css/bootstrap.min.css‘ %}">
    <link rel="stylesheet" href="{% static ‘mystyle.css‘ %}">
</head>
<body>
<div class="container reg-form">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form novalidate action="/register/" method="post" class="form-horizontal" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="{{ form_obj.username.id_for_label }}">
                        {{ form_obj.username.label }}
                    </label>
                    <div class="col-sm-8">
                        {{ form_obj.username }}
                        <span class="help-block">{{ form_obj.username.errors.0 }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="{{ form_obj.password.id_for_label }}">
                        {{ form_obj.password.label }}
                    </label>
                    <div class="col-sm-8">
                        {{ form_obj.password }}
                        <span class="help-block">{{ form_obj.password.errors.0 }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="{{ form_obj.re_password.id_for_label }}">
                        {{ form_obj.re_password.label }}
                    </label>
                    <div class="col-sm-8">
                        {{ form_obj.re_password }}
                        <span class="help-block">{{ form_obj.re_password.errors.0 }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="{{ form_obj.email.id_for_label }}">
                        {{ form_obj.email.label }}
                    </label>
                    <div class="col-sm-8">
                        {{ form_obj.email }}
                        <span class="help-block">{{ form_obj.email.errors.0 }}</span>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="id_avatar">
                        头像
                    </label>
                    <div class="col-sm-8">
                        <label for="id_avatar" id="id_avatar_lab">
                            <img id="id_avatar-img"  src="{% static ‘images/default.jpg‘ %}" >
                        </label>
                        <input type="file" name="avatar" id="id_avatar" style="display: none">
                        <span class="help-block"></span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">注册</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

  在视图函数里面

def register(request):
    if request.method == ‘POST‘:
        form_obj = forms.RegForm(request.POST)
        # 检验
        if form_obj.is_valid():
            # 检验通过
            # 去数据库创建一个新的用户
            # 删除多余的字段
            form_obj.cleaned_data.pop(‘re_password‘)
            models.UserInfo.objects.create_user(**form_obj.cleaned_data)
        else:
            # 将错误的信息返回到注册页面
            return render(request, ‘register.html‘, {"form_obj": form_obj})
    form_obj = forms.RegForm()
    return render(request, ‘register.html‘, {"form_obj": form_obj}) 

form_obj.is_valid()的执行顺序:
  1. 先按照form类中定义的字段顺序,依次校验每一个字段(内置的校验规则)
  2. 每个字段先校验内置的规则, 然后字校验clean_开头的规则
  3. 整个for循环走完之后, 再调用form类中定义的clean()方法

 

即可完成校验两次密码是否一致的功能

相关推荐