有什么办法可以在表单构造函数中更改字段的 *min_length* 参数?这不起作用:
def __init__(self, *args, **kwargs):
super(CreateTeamForm, self).__init__(*args, **kwargs)
self.fields['primary_color'].min_length = 4
有什么办法可以在表单构造函数中更改字段的 *min_length* 参数?这不起作用:
def __init__(self, *args, **kwargs):
super(CreateTeamForm, self).__init__(*args, **kwargs)
self.fields['primary_color'].min_length = 4
尝试validators
在方法中设置字段的属性__init__
。
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