Zags
Zags

Reputation: 41338

Django ModelForm doesn't Work with Decimal Field

I have a Django model with a DecimalField like so:

CHOICES = [
    ("0.1", "0.1"),
    ("0.2", "0.2"),
    ("0.3", "0.3"),
    ...
]

class MyModel(Model)
    field = models.DecimalField(
        max_digits=10,
        default="1.0",
        decimal_places=1,
        choices=CHOICES
    )

I then have a ModelForm

class MyForm(ModelForm):
    class Meta:
        model = MyModel
        exclude = []

When I try to save the form, I get the following error:

Select a valid choice. 0.1 is not one of the available choices.

"0.1" is in my choices. What is wrong with my setup?

Upvotes: 1

Views: 642

Answers (1)

Zags
Zags

Reputation: 41338

While the string representations of the decimals will pass the form validation of Django's ChoiceField, it won't pass the validation of the ModelForm. You need to use Decimal objects instead of strings:

from decimal import Decimal

CHOICES = [
    (Decimal("0.1"), "0.1"),
    (Decimal("0.2"), "0.2"),
    (Decimal("0.3"), "0.3"),
    ...
]

class MyModel(Model)
    field = models.DecimalField(
        max_digits=10,
        default=Decimal("1.0"),
        decimal_places=1,
        choices=CHOICES
    )

Upvotes: 2

Related Questions