我制作了一个扩展 UserCreationForm 的表单,我想验证客户端的输入。我怎样才能做到这一点?当我验证password1时,它工作正常,但由于某种原因,我无法检查字段是否丢失。提前致谢。
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def validate(self,password):
return self.short_enough(password) and self.has_lowercase(password) and self.has_uppercase(password) and self.has_numeric(password) and self.has_special(password)
def short_enough(self,pw):
return len(pw) == 8
def has_lowercase(self,pw):
'Password must contain a lowercase letter'
return len(set(string.ascii_lowercase).intersection(pw)) > 0
def has_uppercase(self,pw):
'Password must contain an uppercase letter'
return len(set(string.ascii_uppercase).intersection(pw)) > 0
def has_numeric(self,pw):
'Password must contain a digit'
return len(set(string.digits).intersection(pw)) > 0
def has_special(self,pw):
'Password must contain a special character'
return len(set(string.punctuation).intersection(pw)) > 0
def clean(self):
cleaned_data = super(UserRegisterForm, self).clean()
username = cleaned_data.get('username')
email = cleaned_data.get('email')
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get("password2")
if username == None or email == None or password1 == None or password2 == None:
raise forms.ValidationError("Some fields are missing" )
if not self.validate(password1):
raise forms.ValidationError("Password must be 8 characters(1 upper, 1 lower, 1 number, 1 special character)" )
else:
return cleaned_data
料青山看我应如是
相关分类