Django form.is_valid 持续抛出 KeyError

1 投票
1 回答
2655 浏览
提问于 2025-04-17 02:32

我在我的视图中有这段代码:

def add_intern(request):
    if request.method == 'POST':
        form = InternApplicationForm(request.POST)
        if form.is_valid():
            form.save()
            form = InternApplicationForm()
    else:
        form = InternApplicationForm()

    return render_to_response('application.html', {'form': form},
                              context_instance = RequestContext(request))

这个表单是一个 ModelForm,而它背后的模型里有一个 IntegerField
当我提交一个空值的表单时,验证消息会正常显示。

但是,当我提交一个非整数值的表单时,我得到了这个错误:

在 / 处发生 KeyError

'invalid'

这让我有点惊讶,因为代码在调用 is_valid() 时似乎崩溃了,我原以为这个调用是安全的(也就是说,如果有问题应该返回 False,而不是直接崩溃)。我该怎么解决这个问题呢?

错误追踪信息

Django Version: 1.3
Python Version: 2.6.5

File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/dan/www/ints/backend/views.py" in add_intern
  14.         if form.is_valid():
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in is_valid
  121.         return self.is_bound and not bool(self.errors)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in _get_errors
  112.             self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in full_clean
  267.         self._clean_fields()
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/forms.py" in _clean_fields
  284.                     value = field.clean(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/fields.py" in clean
  169.         value = self.to_python(value)
File "/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/forms/fields.py" in to_python
  248.             raise ValidationError(self.error_messages['invalid'])

Exception Type: KeyError at /
Exception Value: 'invalid'

1 个回答

7

好的,我终于搞清楚了。

我按照这个建议来设置我自定义的验证错误信息。
所以我有了这样的代码:

def __init__(self, *args, **kwargs):
    super(InternApplicationForm, self).__init__(*args, **kwargs)
    for field in self.fields.values():
        field.error_messages = {'required':'*'}

这段代码为所有字段设置了相同的必填字段验证信息。

当错误类型不同(比如说,非整数时出现的invalid)时,Django会查看我提供的字典——结果你猜怎么着,KeyError。因为在字典里没有invalid的错误信息(这完全是我的错)。

所以解决办法是

        field.error_messages = {'required': '*', 'invalid': "That's not a number, sir."}

(可能还有其他错误信息的键

撰写回答