Django - change min_length in form __init__?

笑着哭i 提交于 2019-12-04 13:13:16

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!