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.
# 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
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 %}
All done!
Top comments (0)