Django Modelform 在 FloatField 上设置最小值

Django Modelform setting minimum Value on FloatField

我正在尝试在我的模型表单中设置表单级别的 min_value 属性。

Forms.py

class ProductForm(forms.models.ModelForm):
    class Meta:
        model = Artikel
        localized_fields = '__all__'
        fields = ('price',)

Model.py

class Artikel(models.Model):
    price = models.FloatField(help_text ='Price')

我如何设置模型以限制模型允许的值? 我希望用户只输入大于或等于 0.01 的值。 我不想限制数据库级别,因为我不想在这方面限制自己。

除了在小部件上设置 'min' 属性外,还覆盖表单的 clean_fieldname() 方法:

class ProductForm(forms.models.ModelForm):

        def __init__(self, *args, **kwargs):
            super(ProductForm, self).__init__(*args, **kwargs)
            self.fields['price'].widget.attrs['min'] = 0.01


        def clean_price(self):
            price = self.cleaned_data['price']
            if price < 0.01:
                raise forms.ValidationError("Price cannot be less than 0.01")
            return price

        class Meta:
            model = Artikel
            localized_fields = '__all__'
            fields = ('price',)

Doc 说:

The clean_<fieldname>() method is called on a form subclass – where is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).

您可以覆盖 ModelForm 的 init 方法。这会将字段上的 min 属性设置为 10:

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['price'].widget.attrs['min'] = 10

执行此操作的简单方法是在字段上设置验证器并提供自定义错误消息:

class ProductModelForm(forms.ModelForm):
   price = forms.FloatField(min_value=0.01,
                            error_messages={'min_value': u'Price cannot be less than 0.01'})