我正在尝试覆盖子类中的“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
答案 0 :(得分:2)
您的max_value
设置正确,问题是您没有更新验证器
__init__
的{{1}} IntegerField
是FloatField
的父亲{/ 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_value
和min_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