form组件类 钩子函数验证

    # 全局钩子
    def clean(self):
        pwd = self.cleaned_data.get("password")
        re_pwd = self.cleaned_data.get("re_password")
        if re_pwd and re_pwd == pwd:
            return self.cleaned_data
        else:
            self.add_error('re_password', "两次密码不一致")
            raise ValidationError("两次密码不一致")
from django import forms
 
class LoginForm(forms.Form):
    username = forms.CharField(label='username', max_length=100)
    password = forms.CharField(label='password', max_length=100)
     
    #钩子函数为对应字段添加判断条件
    def clean_username(self):
        if len(self.cleaned_data.get("username"))>5:
            print(self.cleaned_data.get("password"))
            return self.cleaned_data.get("username")#局部钩子返回值
    def clean_password(self):
        pass
    #全局钩子函数
    def clean(self):
        if self.cleaned_data["password"] == self.cleaned_data["repeat_password"]:
            return self.cleaned_data#【全局钩子返回值】
    
#定义局部的钩子
  def clean_username(self):
        print('这是clean_username')
        if "alex" in self.cleaned_data['username']:
            raise ValidationError('含有非法字符!!!!!!')
        return self.cleaned_data['username']

#定义全局的钩子,
    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')

        if re_pwd == pwd:
            return self.cleaned_data
        self.add_error('re_pwd', '两次密码不一致!!!!')
        raise ValidationError("两次密码不一致")

 

posted @ 2018-11-10 11:58  dmyHero  阅读(327)  评论(0编辑  收藏  举报