Edwin Cruz
Edwin Cruz

Reputation: 517

Changing max_length on a CharField for a ModelForm

I have defined the max_length on a field to be 50 in the model definition. When a form is created it takes those attributes to make the fields, but I would like to overwrite that max_length for that specific form without changing the model itself.

This is what I have in my model

text_field01 = models.CharField(max_length=50, default="")
text_field02 = models.CharField(max_length=50, default="")

I tried overwriting the widget with a new widget in my forms.py but that threw an error. I also tried it in the init but that seemed to have no effect. I am a bit stuck, any help would be greatly appreciated.

EDIT

At first I tried setting the widgets in class meta as shown below.

widgets = {
'text_field01': forms.CharField(max_length=10)

This produced an error "CharField" object has no attribute 'is_hidden'

Then I tried doing it in init as shown below.

        def __init__(self, *args, **kwargs):
            super(AutomationForm, self).__init__(data=data, files=files, *args, **kwargs)
            if self.instance:
                if self.fields['text_field01']:
                    self.fields['text_field01'].max_length = 2

Which simply had no effect.

Upvotes: 3

Views: 2610

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can create a ModelForm, and override the value for the max_length=… parameter [Django-doc]:

class MyModelForm(forms.ModelForm):
    text_field01 = forms.CharField(max_length=25)

    class Meta:
        model = MyModel
        fields = '__all__'

The max_length you define in the ModelForm can only be less than or equal to the one in the Model itself, since validation in the model has to succeed as well.

Upvotes: 2

Related Questions