Take this very simple form for example:
class SearchForm(Form):
q = forms.CharField(label='search')
This gets rendered in the template:
<input type="text" name="q" id="id_q" />
However, I want to add the placeholder attribute to this field with a value of Search so that the HTML would look something like:
<input type="text" name="q" id="id_q" placeholder="Search" />
Preferably I would like to pass the placeholder value in to CharField in the form class through a dictionary or something like:
q = forms.CharField(label='search', placeholder='Search')
What would be the best way to accomplish this?
Look at the widgets documentation. Basically it would look like:
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a
widgetsattribute containing a<field name> => <widget instance>mapping directly on theMetaof yourModelFormsub-class.