Reputation: 701
I'm trying override the "max_value" attribute in the child class without success. What I'm doing wrong?
Parent Class
class ParentForm(forms.Form):
width = forms.FloatField(label='Width (B)', max_value=100, min_value=5)
# others fields
Child Class
class ChildForm(ParentForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['width'].max_value = 50
Upvotes: 1
Views: 481
Reputation: 15390
Your max_value
is set correctly, the issue is that you don't update validator
In __init__
of IntegerField
which is parent of FloatField
it does this
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))
So for fully updating max_value
and min_value
you need also update validators, here is one approach
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
Upvotes: 2
Reputation: 3941
Pass class name and self in super
class ChildForm(ParentForm):
def __init__(self, *args, **kwargs):
super(ChildForm, self).__init__(*args, **kwargs)
self.fields['width'].max_value = 50
Upvotes: -1