Python - Django - form 组件自定义校验
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>
查看 forms.py 的源码
如果有个函数以 clean_ 开头,而名字后面跟的是 cleaned_data 的 key,就会执行该函数
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="密码", error_messages={ "min_length": "密码不能少于6位!", "required": "该字段不能为空" }, widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True) ) re_password = forms.CharField( min_length=6, label="确认密码", error_messages={ "required": "该字段不能为空" }, widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True) ) mobile = forms.CharField( label="手机号", # 自定义正则匹配规则 validators=[ RegexValidator(r'^[0-9]+$', "手机号必须是数字"), # 判断手机号是否为数字 RegexValidator(r'^1[3-9][0-9]{9}$', "手机格式有误") # 判断手机号是否为 1 和 3-9 开头的十一位数 ], error_messages={ "required": "该字段不能为空", }, widget=widgets.TextInput(attrs={"class": "form-control"}) ) # 判断用户名信息 def clean_username(self): value = self.cleaned_data.get("username") if "admin" in value: raise ValidationError("用户名不能含有敏感信息") def reg2(request): form_obj = RegForm() # GET 请求 if request.method == "POST": form_obj = RegForm(request.POST) # 让 form 来帮我们进行校验 if form_obj.is_valid(): # 如果通过校验 # 所有经过校验的数据都保存在 form_obj.cleaned_data print(form_obj.cleaned_data) models.UserInfo.objects.create(**form_obj.cleaned_data) return HttpResponse("注册成功") return render(request, "reg2.html", {"form_obj": form_obj})
在 form 类中添加了一个 clean_username 函数来判断处理 username
运行结果:
重写父类的 clean 方法:
查看 forms.py 中的源码
这里的 clean 方法只在最后的时候返回了 cleaned_data,中间也没有什么操作
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="密码", error_messages={ "min_length": "密码不能少于6位!", "required": "该字段不能为空" }, widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True) ) re_password = forms.CharField( min_length=6, label="确认密码", error_messages={ "required": "该字段不能为空" }, widget=widgets.PasswordInput(attrs={"class": "form-control"}, render_value=True) ) mobile = forms.CharField( label="手机号", # 自定义正则匹配规则 validators=[ RegexValidator(r'^[0-9]+$', "手机号必须是数字"), # 判断手机号是否为数字 RegexValidator(r'^1[3-9][0-9]{9}$', "手机格式有误") # 判断手机号是否为 1 和 3-9 开头的十一位数 ], error_messages={ "required": "该字段不能为空", }, widget=widgets.TextInput(attrs={"class": "form-control"}) ) # 判断用户名信息 def clean_username(self): value = self.cleaned_data.get("username") if "admin" in value: raise ValidationError("用户名不能含有敏感信息") # 重写父类的 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("两次密码不一致")) self.add_error("re_password", ValidationError("两次密码不一致")) raise ValidationError("两次密码不一致") return self.cleaned_data def reg2(request): form_obj = RegForm() # GET 请求 if request.method == "POST": form_obj = RegForm(request.POST) # 让 form 来帮我们进行校验 if form_obj.is_valid(): # 如果通过校验 # 所有经过校验的数据都保存在 form_obj.cleaned_data print(form_obj.cleaned_data) models.UserInfo.objects.create(**form_obj.cleaned_data) return HttpResponse("注册成功") return render(request, "reg2.html", {"form_obj": form_obj})
在 form 类中重构父类的 clean 方法,来对密码部分进行校验
如果两次的密码不同,运行结果: