Sometimes I just want to add a placeholder to a form field.

Yes, I can use a form widget like below:

from django import forms
from django.utils.translation import gettext_lazy as _

class AddKeysForm(forms.ModelForm):
    label = forms.CharField(widget=forms.TextInput(attrs={"placeholder": _("Label")}))

However sometimes it’s over-engineering for only one html attribute and also it’s good to have a simple way to create placeholder in html.

Here is how to make a templatetag which lets you add the html placeholder attribute to your form field inputs and textareas in a Django/Jinja html template.

from django import template

register = template.Library()

def placeholder(value, token):
    """ Add placeholder attribute, esp. for form inputs and textareas """
    value.field.widget.attrs["placeholder"] = token
    return value

And you can implement it in your templates like below:

<!-- someproject/someapp/templates/ -->
{% for field in form %}
  <div class="form-group">
    <div class="text-left alert-danger">
      {{ field.errors }}
    {{ field|placeholder:"Label" }}
{% endfor %}

All done!