Django Modelform在FloatField上设置最小值

2024-04-18 20:02:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在表单.py在

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

在模型.py在

^{pr2}$

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


Tags: py表单fieldsmodel属性valuemodelsforms
3条回答

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

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

除了在widget上设置'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

相关问题 更多 >