Take this very simple form for example:
class SearchForm(Form):
q = forms.CharField(label=\'search\')
This gets rendered in the templat
For a ModelForm, you can use the Meta class thus:
from django import forms
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
widgets = {
'name': forms.TextInput(attrs={'placeholder': 'Name'}),
'description': forms.Textarea(
attrs={'placeholder': 'Enter description here'}),
}
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
More writing, yes, but the separation allows for better abstraction of more complicated cases.
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
The other methods are all good. However, if you prefer to not specify the field (e.g. for some dynamic method), you can use this:
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@address.nl'
It also allows the placeholder to depend on the instance for ModelForms with instance specified.
It's undesirable to have to know how to instantiate a widget when you just want to override its placeholder.
q = forms.CharField(label='search')
...
q.widget.attrs['placeholder'] = "Search"
class FormClass(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
}
You can use this code to add placeholder attr for every TextInput field in you form. Text for placeholders will be taken from model field labels.
class PlaceholderDemoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field:
if type(field.widget) in (forms.TextInput, forms.DateInput):
field.widget = forms.TextInput(attrs={'placeholder': field.label})
class Meta:
model = DemoModel