简体   繁体   English

Django Modelform 在 FloatField 上设置最小值

[英]Django Modelform setting minimum Value on FloatField

i am trying to set the min_value Attribute on Form level within my modelform.我正在尝试在我的模型表单中设置表单级别的 min_value 属性。

Forms.py表单.py

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

Model.py模型.py

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

How can i setup the modelform that i can constrain the values allowed on the modelform?我如何设置模型表格以限制模型表格上允许的值? I want the user to only enter values greater than or equal to 0.01.我希望用户只输入大于或等于 0.01 的值。 I dont want to restricted on Database Level cause i dont want to limit myself in that regard.我不想限制在数据库级别,因为我不想在这方面限制自己。

You can override the ModelForm's init method.您可以覆盖 ModelForm 的init方法。 This will set the min attribute on the field to 10:这会将字段上的min属性设置为 10:

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

In addition to setting 'min' attribute on widget, also override form's clean_fieldname() method:除了在小部件上设置 '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 says: Doc说:

The clean_<fieldname>() method is called on a form subclass – where is replaced with the name of the form field attribute.在表单子类上调用clean_<fieldname>()方法 - 其中替换为表单字段属性的名称。 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).您将需要在 self.cleaned_data 中查找字段的值,并记住此时它将是一个 Python 对象,而不是表单中提交的原始字符串(它将在cleaned_data 中,因为通用字段 clean() 方法,上面已经清理过一次数据)。

The simple way to do this is to set the validator on the field and provide a custom error message:执行此操作的简单方法是在字段上设置验证器并提供自定义错误消息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM