我有一个带有DecimalField的Django模型,如下所示:
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
)
然后我有了一个ModelForm
class MyForm(ModelForm):
class Meta:
model = MyModel
exclude = []
当我尝试保存表单时,出现以下错误:
Select a valid choice. 0.1 is not one of the available choices.
“ 0.1”是我的选择。我的设置有什么问题?
答案 0 :(得分:1)
虽然小数的字符串表示形式将通过Django ChoiceField的形式验证,但不会通过ModelForm的验证。您需要使用小数对象而不是字符串:
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
)