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


Question

I'm outputting fields of a form in a template like this {{ form.first_name }} and I'd like to add a class (eg. blueprint's span-x-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion {{ form.first_name|add_class:"span-4" }}? (I just want to know if Django's developers or anybody has thought of that yet without my knowledge before doing it on my own)

1
32
3/16/2013 4:55:15 PM

Accepted Answer

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
22
10/21/2012 9:20:42 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon