I have a parameter that I am passing in to the form. It is a dictionary to configure the form.
How can I set the max_length of a field using a value from the dictionary?
class StepTwoForm(forms.Form):
number = forms.CharField()
def __init__(self, *args, **kwargs):
if 'config' in kwargs:
config = kwargs.pop('config')
super(StepTwoForm, self).__init__(*args, **kwargs)
self.fields['number'].max_length = config['MAX_LENGTH']
I also just tried hardcoding the max_length to an arbitrary value which didn’t work either.
Or am I going about this the wrong way?
That will work, however you need to move the
super(..)call outside of the condition, otherwise the form won’t get setup properly.UPDATE
It looks like
max_lengthandmin_lengthare used upon initialization, so it’s too late to set themax_lengthparameter. You need to manually add the validator. I’ve updated the code to reflect the change. Here is the relevant code in Django: https://github.com/django/django/blob/master/django/forms/fields.py#L186-L192