1

I've looked everywhere for a simple way to add a placeholder text element to a Django Form input field. There are several examples that look to modify the model forms or use add-ins. I've pieced together several disparate examples to come up with the following...

This is my first custom template tag and before I add a lot of template changes I'd like to verify that this is correct:

templatetags/placeholder.py

from django.template import Library
import re

register = Library()

def placeholder(value, token):
    value.field.widget.attrs["placeholder"] = token
    return value

register.filter(placeholder)

templates/my_app/customer_form.html (implementing Bootstrap)

<div class="container">
    <h5>Add a New Customer</h5>
    <form method="post">{% csrf_token %}
        <table class="table table-borderless table-sm table-half">
            <tr><td>{{ form.customer | placeholder:'Customer Name' }}</td></tr>
            <tr><td>{{ form.address1 | placeholder:'Address' }}</td></tr>
            <tr><td>{{ form.address2 | placeholder:'Address' }}</td></tr>
            <tr><td>{{ form.city | placeholder:'City' }}</td></tr>
            <tr><td>{{ form.state | placeholder:'State' }}</td></tr>
            <tr><td>{{ form.zip | placeholder:'Zip' }}</td></tr>
        </table>
        <input type="submit" class="btn btn-outline-primary" value="Add" />
    </form>
</div>

Firefox

enter image description here

A couple of things I noted:

a) It looks like I can (i) use field tags in the custom tag and (ii) I can use plain text.

b) No space between the custom tag name and the value. If there is a space it throws TemplateSyntaxError that placeholder requires 2 arguments, 1 provided. (?)

My question is: all the other examples on SO use field.widget.attrs in the Class __init__ definitions of the Form (or elsewhere in the views/models) and not through a custom tag - is there a design issue with using a custom tag, is it just bad form or otherwise fine?

Bill Armstrong
  • 1,615
  • 3
  • 23
  • 47

1 Answers1

0

I've now used both the custom template tags and passing in pre-formatted context items. I've come to the conclusion that there isn't an answer to this question.

If I have to write the code, it is easier to write it in the specific context, unless it is repeating, then either as a separate module or a template tag - either has about the same effort (for me).

Importable custom template tags do have the advantage if they are already written and can be imported - such as {% load humanize %}.

Bill Armstrong
  • 1,615
  • 3
  • 23
  • 47