Adding a placeholder to form fields in Django

HTML placeholders in form inputs can be super useful to let the user know what kind of value you are expecting. Setting a placeholder attribute on a HTML element is straightforward, but in Django you normally let a Form class deal with rendering your HTML form.

Therefore, in order to set a placeholder value for a form field in Django you should pass the placeholder as an attribute to a form widget.

from django import forms


class ApiCredentialsForm(forms.Form):
    key = forms.CharField(widget=forms.PasswordInput(
      attrs={'placeholder': '*******'}))
    token = forms.CharField(widget=forms.PasswordInput(
      attrs={'placeholder': '*******'}))

See Also

6 Non-Programming Books for Programmers