Adding css classes to formfields in Django Templates

I'm in the process of making two.bootstrap support Bootstrap 3. A lot has changed but one of the most significant changes may be the requirement that form controls (like input) must have a class="formcontrol" to be rendered properly. 

When using Django forms, it's often unavoidable to have to construct the form explicitly. So in stead of

{{form}}

you iterate over the individual fields and apply some structure/style

{% for field in form.fields %}
<div do-your-styling>
{{field}}
</div>
{% endfor %}

This is accepable, you can do this generically for any form and leave the actual rendering of the form field to django (which includes the widget, pre-filling the value, and so on)

With Bootstrap 2 it was sufficient to wrap any form control in a div with class="controls":

<div class="controls">
{{ field }}
</div>

But bootstrap 3 requires something like

<input class="form-control" ...>

which means somehow this bootstrap specific class has to be added/"injected" to the rendered formfield.

Django makes this simple, just add an extra attr to the fields widget. But all of a sudden you have to update all your current/future form definitions, explicitly fix your modelforms. Equally bad, you have to explicitly apply some frontend specific styling (and bootstrap/framework specific styling!) in your code!

myfield = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

It would be nicer to be able to do this in the template itself, without having to reconstruct the entire widget. For this, I created a simple filter, "addcss":

from django import template
register = template.Library()

@register.filter(name='addcss')
def addcss(field, css):
return field.as_widget(attrs={"class":css})

Put this in your app's templatetags/ folder and you can now do

{{field|addcss:"form-control"}}

 

For now it's a quick hack. It works for me and doesn't modify the field itself, but it does render the field into a string so you cannot chain the filter. I will probably make this a proper package with some extra features and tests.

 

 

Last updated Oct. 2, 2013, 10:28 a.m. | filed under django | django bootstrap templates bootstrap3 form-control fields css
comments powered by Disqus