Django form.is_valid不断抛出KeyError

时间:2011-09-18 17:31:11

标签: python django django-forms django-1.3 django-validation

我的观点中有这个代码:

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      

'无效'

令我感到惊讶的是,代码似乎在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 个答案:

答案 0 :(得分:4)

好的,所以我把它钉了下来。

我跟着this advice设置了自定义错误消息以进行验证 所以我有这个代码:

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."}

(可能还有other error message keys