tags:

views:

319

answers:

2

Hi,

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?

+1  A: 

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")
Seth
Thanks, that was the problem. I tried it and it works. Additionally you pointed me in the right direction and I switched to Float in the model field, since I do not need decimal. With float it works with the initial setting.
Tom Tom
A: 

try:

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

decimal places = the number of digits following the point

max digits = total digits

In your examples you have 2 total digits and 1 digit following the point

Antony Hatchkins