from django import forms # 导入表单模块
from django.core.exceptions import ValidationError class RegisterForm(forms.Form): # 自定义表单类,并继承forms.Form
email = forms.EmailField(widget=forms.EmailInput(
attrs={"class": "form-control"})) username = forms.CharField(min_length=4, max_length=12, widget=forms.TextInput(
attrs={"class": "form-control"})) password = forms.CharField(min_length=6, widget=forms.PasswordInput(
attrs={"class": "form-control"})) password2 = forms.CharField(min_length=6, widget=forms.PasswordInput(
attrs={"class": "form-control"})) valid_code = forms.CharField(widget=forms.TextInput(
attrs={"class": "form-control"})) def __init__(self, request, *args, **kwargs):
# 如果需要额外接收参数,要重写构造器函数
# 这里额外接收一个参数,用于从request.sesssion中提取之前保存的验证码
super(RegisterForm,self).__init__(*args, **kwargs)
self.request = request # 自定义方法(局部钩子),密码必须包含字母和数字
def clean_password(self):
if self.cleaned_data.get('password').isdigit() or self.cleaned_data.get('password').isalpha():
raise ValidationError('密码必须包含数字和字母')
else:
return self.cleaned_data['password'] def clean_valid_code(self): # 检验验证码正确;之前生成的验证码保存在了了session中
if self.cleaned_data.get('valid_code').upper() == self.request.session.get('valid_code'):
return self.cleaned_data['valid_code']
else:
raise ValidationError('验证码不正确') # 自定义方法(全局钩子, 检验两个字段),检验两次密码一致;
def clean(self):
if self.cleaned_data.get('password') != self.cleaned_data.get('password2'):
raise ValidationError('密码不一致')
else:
return self.cleaned_data # 注意,上面的字典取值用get, 因为假如在clean_password中判断失败,那么没有返回值,最下面的clean方法直接取值就会失败s