1 回答

TA貢獻(xiàn)1772條經(jīng)驗 獲得超8個贊
好的,您的模板看起來不錯,只是在表單中添加了一些內(nèi)容。
為了簡化我添加到您定義的電子郵件字段的代碼required=True,并將相同的參數(shù)設(shè)置到__init__其余字段的方法中,這將根據(jù)需要執(zhí)行所有字段,您可以擺脫自定義的“空值”驗證clean
class UserRegisterForm(UserCreationForm):
? ? email = forms.EmailField(required=True)
? ? class Meta:
? ? ? ? model = User?
? ? ? ? fields = ['username', 'email', 'password1', 'password2']
? ? def __init__(self, *args, **kwargs):
? ? ? ? super().__init__(*args, **kwargs)
? ? ? ? self.fields['username'].required = True
? ? ? ? self.fields['password1'].required = True
? ? ? ? self.fields['password2'].required = True
? ? 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()
? ? ? ? password1 = cleaned_data.get('password1')
? ? ? ? password2 = cleaned_data.get("password2")? ? ? ? ??
? ? ? ? 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
另一方面,要進(jìn)行單字段驗證,我建議您使用 django 提供的方法clean_<fieldname>。
添加回答
舉報