Skip to content

Instantly share code, notes, and snippets.

@TimFletcher
Created August 6, 2014 22:24
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save TimFletcher/034e799c19eb763fa859 to your computer and use it in GitHub Desktop.
Save TimFletcher/034e799c19eb763fa859 to your computer and use it in GitHub Desktop.
Django template filter to add attributes to form fields
# From http://vanderwijk.info/blog/adding-css-classes-formfields-in-django-templates/#comment-1193609278
from django import template
register = template.Library()
@register.filter(name='add_attributes')
def add_attributes(field, css):
attrs = {}
definition = css.split(',')
for d in definition:
if ':' not in d:
attrs['class'] = d
else:
t, v = d.split(':')
attrs[t] = v
return field.as_widget(attrs=attrs)
@neuman
Copy link

neuman commented Feb 16, 2015

This is great! Any interest in making it a standalone package?

@shmilyoo
Copy link

shmilyoo commented Mar 4, 2015

can not add class to 'widget=forms.RadioSelect'
input is ok
why? can you fix it ?

@shmilyoo
Copy link

shmilyoo commented Mar 4, 2015

for example,you want to add "style:width:20px",
there will be a collision between the Colon in the template and the colon in the python code.
so,you can change the : to = in the register.

@markuz
Copy link

markuz commented Feb 16, 2018

There is also a problem if you want to add multiple classes (like form-control selectpicker) (https://silviomoreto.github.io/bootstrap-select/examples/#styling).

What I've done is use collections.defaultdict(str) instead of a simple dict, then just add to the css attribute.

def addcss(field, css):
    try:
        attrs = collections.defaultdict(str)
        definition = css.split(',')
        for d in definition:
            if ':' not in d:
                attrs['class'] += " %s"%d
            else:
                t, v = d.split(':')
                attrs[t] = v
        return field.as_widget(attrs=attrs)
    except Exception as e:
        return field

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment