5

Is there any way, to change the field's *min_length* argument inside form constructor? That doesn't work:

def __init__(self, *args, **kwargs):
    super(CreateTeamForm, self).__init__(*args, **kwargs)
    self.fields['primary_color'].min_length = 4
tunarob
  • 2,768
  • 4
  • 31
  • 48

1 Answers1

8

Try setting the field's validators attribute in the __init__ method.

from django.core.validators import MinLengthValidator

class MyForm(forms.Form):
    primary_color = forms.CharField()
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        # get all the validators on the field which are not MinLengthValidator
        validators = [v for v in self.fields['primary_color'].validators if not isinstance(v, MinLengthValidator)]
        min_length = 10
        validators.append(MinLengthValidator(min_length))
        self.fields['primary_color'].validators = validators
Alasdair
  • 298,606
  • 55
  • 578
  • 516