How do I add a placeholder on a CharField in Django?
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.
For a ModelForm, you can use the Meta class thus:
from django import formsfrom .models import MyModelclass MyModelForm(forms.ModelForm): class Meta: model = MyModel widgets = { 'name': forms.TextInput(attrs={'placeholder': 'Name'}), 'description': forms.Textarea( attrs={'placeholder': 'Enter description here'}), }
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.