Django:为什么一个keyerror而不是验证错误?

时间:2013-03-13 10:37:21

标签: django django-forms

为什么在一个字段为空时出现keyerror而不是验证错误?默认情况下,字段应为required=True

class form(forms.ModelForm):
    adminAccount = forms.CharField()
    adminPassword = forms.CharField(widget=forms.PasswordInput)

    def userCheck(self, user, password):
        # do something

    def clean(self):
        self.userCheck(self.cleaned_data['adminAccount'], 
                       self.cleaned_data['adminPassword']) 

1 个答案:

答案 0 :(得分:1)

您的代码正在提升KeyError

self.userCheck(self.cleaned_data['adminAccount'],
               self.cleaned_data['adminPassword'])

因为您在未发布字段时尝试访问self.cleaned_data[field]

documentation provides an example解释了如何验证依赖于多个字段的数据。根据示例,您应该执行以下操作:

cleaned_data = super(form, self).clean()
adminAccount = cleaned_data.get('adminAccount')
adminPassword = cleaned_data.get('adminPassword')

if adminAccount and adminPassword:
    # proceed with your validation

return cleaned_data

另外,请记住Form.clean()必须返回cleaning_data dict。