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

时间:2017-12-16 14:38:17

标签: django

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

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

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

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

我的问题是,这是处理此问题的最佳方式吗?

1 个答案:

答案 0 :(得分:0)

根据文档,password会在dict.get()字段错误字典中添加一个条目。

您应该使用cleaned_datapassword = 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')) 获取价值,以便安全访问它。

document.addEventListener('DOMContentLoaded', () => {
console.log('ready!');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
    if (xhr.readyState === 4)
        document.getElementById('file-data').innerText = xhr.responseText;
    xhr.send();
}
xhr.open('GET', 'file:///E:ada/kk.js', true);
});

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