1. 程式人生 > >form元件類 鉤子函式驗證

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("兩次密碼不一致")