I use a FormSet that contains several forms, each of which has a quantity field, which is defined as follows:
quantity = TypedChoiceField(coerce=int, required=False)
I want to know if there is at least one quantity> 0, so in my pure cheat I write this:
def clean(self):
if sum([form.cleaned_data['quantity'] for form in self.forms]) == 0:
raise forms.ValidationError(_('No products selected'))
So usually this just works, and form.cleaned_data ['quantity'] is int (as set by coerce = int). But every once in a while (just every 2000 requests for this form), I get an exception that tells me:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
On this line, this means that form.cleaned_data ['quantity'] is a string, and sum () is not suitable for summing strings, so it throws an exception. You can verify this yourself by running the python console and typing:
>>> 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'
>>>
, : ? ? django , TypedChoiceField , clean(), .
, , , , , , .
python 2.6 django 1.3.1.
!
, stacktrace:
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:
: TypeError at /****/url
: +: 'int' 'str'