I have to add extra field to my model form. My approach is:
class MyForm(forms.ModelForm):
extra_field = forms.CharField()
class Meta:
model = MyModel
widgets = {
#Does not work
'extra_field': forms.Textarea(attrs={'placeholder': u'Bla bla'}),
}
But it seems that widget definition for extra_field at class Meta is ignored, because i have a bare input tag instead of textarea on a template.
So I apply next approach:
class MyForm(forms.ModelForm):
#It works fine
extra_field = forms.CharField(widget=forms.Textarea())
class Meta:
model = MyModel
It works perfectly for me, but I used to specify widgets for form fields at class Meta declaration. So I wonder:
Why my first approach doesn’t work? What I am doing wrong?
It doesn’t matter if it’s an extra field. This works:
This doesn’t:
This is not documented indeed, that’s the best I could find in the docs that could relate to that behaviour (maybe it doesn’t, it’s just the best i could find):
The implementation of this behaviour is in django/forms/models.py line 219:
After line 206, fields[‘name’].widget is indeed the Textarea specified in Meta.widgets.
At line 219, fields is updated with declared_fields, and fields[‘name’].widget becomes django.forms.widgets.TextInput which is the default for CharField.
Apparently, explicit field definitions have priority.
Thanks for asking, good to know, great question.