Django form.is_valid 不断抛出 KeyError

发布于 2024-12-04 23:34:22 字数 2140 浏览 7 评论 0原文

我的观点是这样的代码:

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'

I have this code in my view:

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

The form is a ModelForm, and the underlying model contains an IntegerField.
When I post a form with empty value, the validation message is displayed just fine.

When I post the form with a non-integer value, I get this:

KeyError at /

'invalid'

It kind of surprises me that the code seems to crash on is_valid() call, which I assumed is safe (i.e. should return False if there is a problem and not just crash). How do I fix this?

Stacktrace

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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

第七度阳光i 2024-12-11 23:34:22

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

我按照此建议进行设置我的自定义验证错误消息。
所以我有这样的代码:

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

(并且可能其他错误消息键)

Okay, so I just nailed it down.

I followed this advice to set my custom error message for validation.
So I had this code:

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

that set the same required field validation message for all fields.

When the error was different (invalid for non-integer), Django looked in the dictionary I supplied—and guess what, KeyError. Because there is no message for invalid there (and that's my fault).

So the fix is

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

(and possibly other error message keys)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文