Django: Adding CSS classes when rendering form fields in a template

Another way is to use the as_widget method on a field to alter it -- simpler and safer than the regex approach, and doesn't require any additional dependencies.

Define a custom template filter:

@register.filter
def add_class(field, class_name):
    return field.as_widget(attrs={
        "class": " ".join((field.css_classes(), class_name))
    })

And in your template:

{{ form.first_name|add_class:"span-4" }}

You can also use as_widget to add other attributes, like placeholder, etc.


You only need to install Django widget_tweaks

pip install django-widget-tweaks

After you can to do something like that on your template:

{{ form.search_query|attr:"type:search" }}

--

Read all about it here.


A few extra notes on how to get going with Lazerscience's very handy solution. Here's how the file looks with dependency imports:

import re
from django.utils.safestring import mark_safe
from django import template
register = template.Library()

class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filter
def add_class(value, css_class):
    string = unicode(value)
    match = class_re.search(string)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, 
                                                    css_class, css_class), 
                                                    match.group(1))
        print match.group(1)
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class, 
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value

I pasted this into a file called add_class.py. The directory structure is: mydjangoproject > general_tools_app > templatetags > add_class.py

general_tools_app is an application which collects useful functionality like this that I add to new django projects.

(The general_tools_app and templatetags directories both have an empty __init__.py file so that they get registered correctly)

In settings.py, my INSTALLED_APPS tuple includes the entry 'mydjangoproject.general_tools_app'.

To use the filter in a template, I add the line {% load add_class %} at the top of the file. If I want to add the class 'delete' to a field, I'd do this

{{ myfield|add_class:'delete' }}

To solve this I made my own template filter, you can apply it on any tag, not just input elements!

class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filter
def add_class(value, css_class):
    string = unicode(value)
    match = class_re.search(string)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, 
                                                    css_class, css_class), 
                                                    match.group(1))
        print match.group(1)
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class, 
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value