Django:为什么一个keyerror而不是验证错误? [英] Django: why a keyerror instead of a validation error?

查看:1034
本文介绍了Django:为什么一个keyerror而不是验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

why comes a keyerror instead of a validation error when one field is empty? The fields should be required=True by default

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']) 


推荐答案

正在提高 KeyError 这里:

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

因为你试图访问 self.cleaned_data [field] 当字段未发布。

Because you're trying to access self.cleaned_data[field] when field was not posted.

文档提供了一个例子,说明了如何验证取决于多个字段的数据。根据示例,您应该执行以下操作:

The documentation provides an example that explains how to validate data that depends on more than one field. According to the examples you should do something like:

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() 必须返回clean_data dict。

Also, remember that Form.clean() must return the cleaned_data dict.

这篇关于Django:为什么一个keyerror而不是验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆