jaa*_*apz 5 python django python-2.6 django-forms
我正在使用一个包含多个表单的FormSet,每个表单都有一个数量字段,其定义如下:
quantity = TypedChoiceField(coerce=int, required=False)
Run Code Online (Sandbox Code Playgroud)
我想知道是否至少有一个数量> 0,所以在我的formset干净,我写这个:
def clean(self):
if sum([form.cleaned_data['quantity'] for form in self.forms]) == 0:
raise forms.ValidationError(_('No products selected'))
Run Code Online (Sandbox Code Playgroud)
所以,通常这只是起作用,而form.cleaned_data ['quantity']是一个int(由coerce = int设置).但每隔一段时间(就像每2000次请求这个表格一样),我得到一个例外,告诉我:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)
在那一行,这意味着form.cleaned_data ['quantity']是一个字符串,sum()不喜欢求和字符串,所以它抛出一个异常.您可以通过启动python控制台并键入以下内容来自行测试:
>>> sum([u'1', u'2'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'unicode'
>>>
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,为什么会发生这种情况?还有为什么这种情况很少发生?django文档告诉我,在调用clean()之前,可以保证强制执行TypedChoiceField,因此不应该这样做.
这个bug很难修复,因为它很难重现,所以我希望你们其中一个人遇到类似的问题.
这是在python 2.6和django 1.3.1上.
提前致谢!
编辑 所以这里是堆栈跟踪:
File "****/handlers/products.py" in process
429. if formset.is_valid():
File "/usr/local/lib/python2.6/dist-packages/django/forms/formsets.py" in is_valid
263. err = self.errors
File "/usr/local/lib/python2.6/dist-packages/django/forms/formsets.py" in _get_errors
241. self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/django/forms/formsets.py" in full_clean
287. self.clean()
File "****/handlers/products.py" in clean
217. if sum([form.cleaned_data['quantity'] for form in self.forms]) == 0:
Run Code Online (Sandbox Code Playgroud)
异常类型:异常处的TypeError /****/url
值:+:'int'和'str'的不支持的操作数类型
根据docsempty_value , a 的
默认值是空字符串,并且该值不是强制的。TypedChoiceField
我认为您有时会得到一个空值,并且引发 TypeError 的字符串就是空字符串。尝试:
quantity = TypedChoiceField(coerce=int, required=False, empty_value=0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
820 次 |
| 最近记录: |