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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With