1
class A:
  min_v = 1
  max_v = 15
  number1 = IntegerField(min_value=min_v, max_value=max_v)

class B(A):
   number2 = IntegerField(min_value=A.min_v, max_value=A.max_v)

class C(B):
  min_v = 2
  max_v = 20

How to make both number1 and number2 to be in range from 2 to 20 in class C?

I'm thinking about two ways:

  1. In __init__ redeclare self.fields['number1'] like IntegerField(min_value=self.min_v)
  2. Set self.fields['number1'].min_value=self.min_v in __init__ and override setattr() to add validator.

What is the best and the cleanest way?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

I thought about it, but it is not passed to widget attrs.
@AndrewFount: that why you need to append the validators: Django only looks at this when you construct a form field. This thus means that if you later set the .min_value and .max_value, it will not validate properly at the backend side. The .min_value and .max_value are necessary for the bounds at the frontend, since these will be used for a <input type="number" min="..." max="...">.
I mean, that widget attrs also should be added: number2.widget.attrs.update({'min': self.min_v, 'max': self.max_v})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.