Django学习笔记之form组件的局部钩子和全局钩子
本文通过注册页面的form组件,查看其中使用的全局钩子和局部钩子。
# Create your views here. class RegForm(forms.Form): username = forms.CharField( min_length=3, label="用户名", help_text=‘‘, error_messages={ "required": "不能为空", "invalid": "格式错误", "min_length": "用户名最短8位" } ) password = forms.CharField( min_length=3, label="密码", help_text=‘6~16个字符,区分大小写‘, error_messages={ "required": "不能为空", "invalid": "格式错误", }, widget=forms.widgets.PasswordInput ) re_password = forms.CharField( min_length=3, label="确认密码", help_text=‘请再次填写密码‘, error_messages={ "required": "不能为空", "invalid": "格式错误", }, widget=forms.widgets.PasswordInput) gender = forms.fields.ChoiceField( choices=((1, "男"), (2, "女"), (3, "保密")), label="性别", initial=3, widget=forms.widgets.RadioSelect ) phone = forms.fields.CharField( label="电话", error_messages={ "required": "不能为空", }, ) email = forms.fields.CharField( label=‘邮箱‘, help_text=‘6~18个字符,可使用字母、数字、下划线‘, widget=forms.widgets.EmailInput, error_messages={ "required": "不能为空", "invalid": "格式错误", }, ) # 批量给form表单里的字段加样式 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter(self.fields): field_obj = self.fields[field] if not isinstance(field_obj, forms.fields.ChoiceField): field_obj.widget.attrs.update({‘class‘: ‘form-control‘}) # 全局钩子,此处用来判断两次输入的密码 def clean(self): pwd = self.cleaned_data.get(‘pwd‘) re_pwd = self.cleaned_data.get(‘re_pwd‘) if pwd != re_pwd: self.add_error(‘re_pwd‘, ‘两次密码不一致‘) raise ValidationError(‘两次密码不一致‘) else: return self.cleaned_data # 局部钩子函数,写给phone的校验函数 def clean_phone(self): phone = self.cleaned_data.get(‘phone‘) if not re.findall(‘^1[0-9]{10}$‘, phone): raise ValidationError("格式错误!") else: return phone
关于钩子函数:
源码里的 forms/forms.py
源码中的钩子函数应用