Colin
Colin

Reputation: 3752

how to make django form override model?

In a django model, I have a field

state = models.CharField(max_length=100, blank=True, null=True)

And I want to keep this max length of 100 in the model and database. But when I display an html form, I want to limit its maxlength to 2.

I do this:

class EditMyThingForm(ModelForm):
    class Meta:
        model = MyThing
        fields = [ 'state' ]
        widgets = { 'state': forms.TextInput(attrs={'maxlength': 2}) }

But no matter what I do, maxlength is 100! Does the Form seriously not override the Model?

Upvotes: 2

Views: 123

Answers (1)

Kamil Zajac
Kamil Zajac

Reputation: 219

Try to override it like this :)

from django import forms


class EditMyThingForm(forms.ModelForm):
    state = forms.CharField(label='State', widget=forms.Textarea, max_length=2)

    class Meta:
        model = MyThing
        fields = ('state', )

Upvotes: 2

Related Questions