Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django combine models.DecimalField with forms -> error: quantize result has too many digits for current context

Tags:

python

django

I want to combine a model decimal field with a forms choice field.

The field in the model:

sum = models.DecimalField(max_digits=2, decimal_places=2)

The field in the form:

sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True)

The choices:

WORK_HOUR_CHOICES = (
    (0, '0'),
    (0.5, '0.5'),
    (1, '1'),
    (1.5, '1.5'),
    (2, '2'),
    (2.5, '2.5')
)

But always when I want to store a value with a decimal place I get this error:

quantize result has too many digits for current context

When I save a 0 or 1 it works fine.

What's wrong?

like image 388
Thomas Kremmel Avatar asked Jan 12 '10 19:01

Thomas Kremmel


1 Answers

It's just a guess, but I bet you need to put Decimals in there:

WORK_HOUR_CHOICES = (
    (Decimal("0"), '0'),
    (Decimal("0.5"), '0.5'),
    (Decimal("1"), '1'),
    (Decimal("1.5"), '1.5'),
    (Decimal("2"), '2'),
    (Decimal("2.5"), '2.5')
)

You can't initialize a Decimal with a float constant, you have to use a string.

>>> from decimal import Decimal
>>> Decimal(1.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\software\Python25\lib\decimal.py", line 578, in __new__
    "First convert the float to a string")
TypeError: Cannot convert float to Decimal.  First convert the float to a string
>>> Decimal("1.5")
Decimal("1.5")
like image 189
Seth Avatar answered Sep 19 '22 06:09

Seth