表单字段验证会导致多字段验证出现问题

问题描述 投票:1回答:1

我正在编写一个注册用户表单,我正在实现一些自己的密码验证(检查用户选择的密码是否足够复杂)。

到目前为止,我只实现了一个要求,即密码需要足够长。如果密码在此要求上失败,则整个站点崩溃。让我解释一下原因。这是表格:

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username','email','password']

    def clean_password(self):
        password = self.cleaned_data['password']

        if len(password) < 8:
            raise forms.ValidationError(_('The password needs to be at least 8 characters long'))

        return password

    def clean(self):
        cleaned_data = super(UserForm, self).clean()
        password = cleaned_data['password']
        confirm_password = cleaned_data['confirm_password']
        if not password == confirm_password:
            raise forms.ValidationError(_('The passwords do not match'))

这是错误:

 File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/forms.py", line 43, in clean
    password = cleaned_data['password']
KeyError: 'password'

clean_password()方法引发错误时,它不会返回密码,这会导致它从self.cleaned_data字典中丢失。我能想出解决这个问题的一种方法:

def clean(self):
    cleaned_data = super(UserForm, self).clean()
    try:
        password = cleaned_data['password']
        confirm_password = cleaned_data['confirm_password']
        if not password == confirm_password:
            raise forms.ValidationError(_('The passwords do not match'))
    except KeyError:
        pass

这样,如果出现错误,程序将不会崩溃。如果密码不匹配,我们将不会收到错误消息,但这应该是无关紧要的,因为用户选择的密码无论如何都是无效的。

我的问题是,这是处理这个问题的最佳方法吗?

django
1个回答
0
投票

根据文档,ValidationError添加了password字段错误字典的条目。

您应该使用dict.get()cleaned_data获取价值以便安全访问它。

password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')

if password and confirm_password and not password == confirm_password:
            raise forms.ValidationError(_('The passwords do not match'))

验证错误将在代码中进一步捕获并作为表单验证错误处理。

© www.soinside.com 2019 - 2024. All rights reserved.