Skip to main content


 

Rilasciato Django 2.0


#django #python



 
#django



 
Good riddance #Python 2 🎉 ✨

#Django #future



 

Add Bootstrap css classes to form fields in django templates


I'm doing a #django project with bootstrap css templates.

I'm using generic edit class based views, like django.views.generic.edit.CreateView.

Now I want to add form-control class to all the fields in template.
I did't found an 'official' way to do it, so I've done the quickest hackish way I found, with a little tweak: a template filter to add css classes to fields.

The original tip I found on The Internet® was
@register.filter
def addcss(field, css):
    return field.as_widget(attrs={''class':css})


Which works, but hei, I cant chain other field-related filters to it.. so:
@register.filter
def addcss(field, css):
    css_class_list = field.field.widget.attrs.get("class", "")
    css_class_list =  css_class_list + " " + css
    field.field.widget.attrs["class"] = css_class_list
    return field


The template:
...
      {% for field in form %}
        <div class="form-group">
          <label for="{{ field.auto_id}}">{{ field.label }}</label>
          {{ field|addcss:"form-control" }}
        </div>
      {% endfor %}
...



 

u use django too?

Not as much I would like to...