Django表单覆盖FloatField max_value属性

时间:2017-06-15 22:56:50

标签: django django-forms

我正在尝试覆盖子类中的“max_value”属性但没有成功。我做错了什么?

父类

class ParentForm(forms.Form):

    width = forms.FloatField(label='Width (B)', max_value=100, min_value=5)
    # others fields

儿童班

class ChildForm(ParentForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['width'].max_value = 50

2 个答案:

答案 0 :(得分:2)

您的max_value设置正确,问题是您没有更新验证器

__init__的{​​{1}} IntegerFieldFloatField的父亲{/ 1}}

def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        if kwargs.get('localize') and self.widget == NumberInput:
            # Localized number input is not well supported on most browsers
            kwargs.setdefault('widget', super(IntegerField, self).widget)
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value))

因此,要完全更新max_valuemin_value,您还需要更新验证程序,这是一种方法

from django.core import validators

class ChildForm(ParentForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        max_value = 50
        self.fields['width'].max_value = max_value
        for validator in self.fields['width'].validators:
            if isinstance(validator, validators.MaxValueValidator):
                validator.limit_value = max_value

答案 1 :(得分:-1)

在超级

中传递班级名称和自我
class ChildForm(ParentForm):

    def __init__(self, *args, **kwargs):
        super(ChildForm, self).__init__(*args, **kwargs)
        self.fields['width'].max_value = 50