[Answered ]-Override min_value and max_value in IntegerField Django

1πŸ‘

βœ…

It might be better to add these bounds as validators to the the bounds in the __init__ method of class A and class B. This will make these transparent to C and furthermore C can for example define another IntegerField for that name and thus specify a different widget for that:

from django.core import validators

class A:
    number1 = IntegerField()
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        number1 = self.fields['number1']
        number1.validators.append(validators.MinValueValidator(self.min_v))
        number1.validators.append(validators.MaxValueValidator(self.max_v))
        number1.widget.attrs['min'] = number1.min_value = self.min_v
        number1.widget.attrs['max'] = number1.max_value = self.max_v

class B(A):
    number2 = IntegerField()
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        number2 = self.field['number2']
        number2.validators.append(validators.MinValueValidator(self.min_v))
        number2.validators.append(validators.MaxValueValidator(self.max_v))
        number2.widget.attrs['min'] = number2.min_value = self.min_v
        number1.widget.attrs['max'] = number2.max_value = self.max_v

Leave a comment