Adding an attribute to the <input> tag for a django ModelForm field

Personally I prefer to use this method:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or '[email protected]'

It required more code if you don't have __init__ yet, but you don't need to specify the widget.


See the documentation

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        widgets = {
            'name': TextInput(attrs={'placeholder': 'name'}),
        }

You could always create your own widget that derives from TextInput and includes the placeholder attribute, and use the widgets dictionary to simply map fields to your new widget without specifying the placeholder attribute for every field.