Django form.is_valid持续抛出KeyError [英] Django form.is_valid keeps throwing KeyError

查看:509
本文介绍了Django form.is_valid持续抛出KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图中有这个代码:

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

form = InternApplicationForm()

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

表单是一个 ModelForm ,底层模型包含一个 IntegerField

当我发布一个带有空值的表单时,验证信息显示得很好。



当我发布非整数值的表单时,我得到这个:


$ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ that that that that that that that that that that that that that that that that that that that that that that that that that that that that that that that that该代码似乎在 is_valid()调用中崩溃,我认为它是安全的(即应该返回 False 如果有问题而不仅仅是崩溃)。如何解决这个问题?



StackTrace



  Django版本:1.3 
Python版本:2.6.5

文件/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6.egg/django/core/handlers /base.pyin get_response
111. response = callback(request,* callback_args,** callback_kwargs)
文件/home/dan/www/ints/backend/views.pyin add_intern
14.如果form.is_valid():
文件/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而不是bool(self.errors)
文件/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6。 egg / django / forms / forms.py在_get_errors
112. self.full_clean()
文件/usr/local/lib/python2.6/dist-packages/Django-1.3-py2。 6.egg / django / forms / forms.pyin full_clean
267. self._clean_fields()
文件/usr/local/lib/python2.6/dist-packages/Django-1.3- py2.6.egg / django的/ F orms / forms.pyin _clean_fields
284. value = field.clean(value)
文件/usr/local/lib/python2.6/dist-packages/Django-1.3-py2.6 .egg / django / forms / fields.pyin clean
169. value = self.to_python(value)
文件/usr/local/lib/python2.6/dist-packages/Django- in-python
248. raise ValidationError(self.error_messages ['invalid'])

异常类型:KeyError at /
异常值:'invalid'


解决方案

,所以我只是把它钉住了。



我遵循设置我的自定义错误消息进行验证。

所以我有这个代码:

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

为所有字段设置相同的必填字段验证消息。



当错误不同( invalid 为非整数),Django查看我提供的字典,并猜测什么, KeyError 。因为没有无效的消息那里(这是我的错)。



所以修复是

  field.error_messages = {'required':'*','invalid':这不是一个数字,先生。 $ b  

(可能其他错误信息键


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'

解决方案

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)

这篇关于Django form.is_valid持续抛出KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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