Search code examples
pythondjangoformsparametersmaxlength

Setting max_length of a form field using a parameter in Django


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?


Solution

  • That will work, however you need to move the super(..) call outside of the condition, otherwise the form won't get setup properly.

    from django.core import validators
    
    class StepTwoForm(forms.Form):
        number = forms.CharField()
    
        def __init__(self, *args, **kwargs):
            config = kwargs.pop('config', {})
            super(StepTwoForm, self).__init__(*args, **kwargs)
            if 'MAX_LENGTH' in config:
                validator = validators.MaxLengthValidator(config['MAX_LENGTH'])
                self.fields['number'].validators.append(validator)
    

    UPDATE

    It looks like max_length and min_length are used upon initialization, so it's too late to set the max_length parameter. 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