Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 590
Bernhard Vallant Avatar asked Nov 08 '10 13:11

Bernhard Vallant


People also ask

How can we load CSS file in our Django templates?

The static folder should be created in your project folder, that's where you can create in static folder a folder called css, and then in the css folder add the css files.

Which function of Django's form class will render a form's fields as a series of P tags?

{{ form. as_p }} – Render Django Forms as paragraph.


2 Answers

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.

like image 146
Cristian Rojas Avatar answered Oct 19 '22 19:10

Cristian Rojas


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
like image 23
Bernhard Vallant Avatar answered Oct 19 '22 19:10

Bernhard Vallant