我有一个相对标准的RegistrationForm,如下所示:
class RegisterForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'username'}), initial='')
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'email'}), initial='')
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'password'}), initial='')
password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'retype password'}), initial='')
当用户忘记填写一个或多个字段时,如何创建一个返回错误的干净方法?(即“您忘记填写电子邮件字段”)
我在 clean() 方法中尝试了以下两个选项(我将使用 password 和 password_repeat 字段作为示例):
password = self.cleaned_data['password']
password_repeat = self.cleaned_data['password_repeat']
# initial values are set to '' for all fields, see above.
if password == '':
raise forms.ValidationError("You forgot to type in a password.")
elif password_repeat == '':
raise forms.ValidationError("You forgot to retype your password.")
第一个选项返回:
/homepage/ 处的 KeyError
'密码'
try:
password = self.cleaned_data['password']
password_repeat = self.cleaned_data['password_repeat']
except KeyError(password):
raise forms.ValidationError("You forgot to fill in the password field.")
第二个选项返回:
/homepage/ 处的 UnboundLocalError
赋值前引用的局部变量“密码”
如果您可以提供允许检查剩余字段的解决方案(以便我可以返回绑定到用户成功提交的数据的表单),则可以加分。