Django:当用户提交未完成的表单时如何引发异常?

sga*_*a62 5 python forms django error-handling

我有一个相对标准的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='')
Run Code Online (Sandbox Code Playgroud)

如何在用户忘记填写一个或多个字段时创建一个返回错误的干净方法?(即"你忘了填写电子邮件字段")

我在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.")
Run Code Online (Sandbox Code Playgroud)

第一个选项返回:

/ 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.")
Run Code Online (Sandbox Code Playgroud)

第二个选项返回:

/ homepage /的UnboundLocalError

在赋值之前引用的局部变量'password'


如果您可以提供允许检查其余字段的解决方案,那么奖励点(以便我可以返回绑定到用户成功提交的数据的表单).

Max*_*cer 5

您可以使用required可用于所有Field类型的属性,这些类型会自动执行此类验证.所以你的代码看起来像:

class RegisterForm(forms.Form):
    username = forms.CharField(
        widget = forms.TextInput(attrs = {'placeholder': 'username'}),
        required = True)
    email = forms.EmailField(
        widget = forms.TextInput(attrs = {'placeholder': 'email'}),
        required = True)
    password = forms.CharField(
        widget = forms.PasswordInput(attrs = {'placeholder': 'password'}),
        required = True)
    password_repeat = forms.CharField(
        widget = forms.PasswordInput(attrs = {'placeholder': 'retype password'}),
        required = True)
Run Code Online (Sandbox Code Playgroud)

注意:我认为您也可以省略这些initial = ''参数,如上所示.

我实际上不确定你为什么会收到你在问题中提到的错误,也许你可以发布你的相关代码views.py?这可能是因为您需要cleaned_data在实现的任何clean方法的最后返回.

我还要说你对这种clean方法的使用并不完全正确.如果您参考表单和字段验证文档的此页面,您会看到验证单个字段时使用的是特定clean_<fieldname>方法,例如clean_password_repeat.clean当验证同时涉及多个字段时,使用该方法是合适的,您可能想要使用的一个示例是检查两个密码字段匹配的输入.

class RegisterForm(forms.Form):
    # field definitions (above)

    def clean(self):
        password = self.cleaned_data['password']
        password_repeat = self.cleaned_data['password_repeat']
        if password != password_repeat:
            raise forms.ValidationError(u"Passwords do not match.")
        return cleaned_data
Run Code Online (Sandbox Code Playgroud)

注意:代码未经过测试.

我希望这可以帮到你!