十进制字段的选择

时间:2018-08-17 09:44:59

标签: python django

models.py

class SomeModel(models.Model):
    price = models.DecimalField(decimal_places=1, max_digits=8)

forms.py

class SomeForm(forms.ModelForm):
    title = forms.CharField(label=_("Title"), required=False)
    price = forms.ChoiceField(choices=[], label=_("Price"))

    class Meta:
        model = SomeModel
        exclude = ('some_fields',)

    def __init__(self, min_price = 10, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)

        price_field = self.fields['price']
        price_field.choices = (
            (i, i) for i in xrange(min_price, 200, 5))

这将引发错误,因为表单发布时的价格值是一个字符串,它没有保存在模型的Decimal字段中。

生成器的类型转换在这里不起作用。有什么解决方案?

0 个答案:

没有答案