Django form fields and templates


Determining the type of a form field object from a Django template requires writing a new filter. Posted by Thomas Sutton on June 22, 2009

I’ve been working with Django for the last little while (or long while) and something that stumped me for a while was a useful, generic approach to marking-up forms in HTML. In particular, making it possible to use CSS to style classes of fields (all checkboxes, for instance, or all date-pickers) effectively. Doing so requires being able to write a selector to pick such elements out, but I found it very difficult to do so.

The only way, as far as I (and the replies on django-users@), is to write a template filter to extract a such a value for you. Thankfully, this it pretty easy:

I can use the above filter to add a class to my form markup:

            <div class="form-field form-{{ field|field_type }}">
                {{ field.label_tag}}
                {{ field.errors }}
                {{ field }}
            </div>

Which I can then use in my CSS to style particular widgets without having to do them one-by-one using ID’s:

This post was published on June 22, 2009 and last modified on January 4, 2019. It is tagged with: django, html, web, forms.