DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Placeholder Templatetags Django

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")}))
    ...
Enter fullscreen mode Exit fullscreen mode

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.

# someproject/someapp/templatetags/placeholder.py
from django import template

register = template.Library()


@register.filter(name="placeholder")
def placeholder(value, token):
    """ Add placeholder attribute, esp. for form inputs and textareas """
    value.field.widget.attrs["placeholder"] = token
    return value
Enter fullscreen mode Exit fullscreen mode

And you can implement it in your templates like below:

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

All done!

Discussion (0)