简体   繁体   中英

Django - change min_length in form __init__?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM