Frage

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?

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top