Assume I have a form
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.Boolea
Use django-widget-tweaks, it is easy to use and works pretty well.
Otherwise this can be done using a custom template filter.
Considering you render your form this way :
form.subject is an instance of BoundField which has the as_widget method.
you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"
from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(value, arg):
css_classes = value.field.widget.attrs.get('class', '').split(' ')
if css_classes and arg not in css_classes:
css_classes = '%s %s' % (css_classes, arg)
return value.as_widget(attrs={'class': css_classes})
And then apply your filter:
{% load myfilters %}
form.subjects will then be rendered with the "MyClass" css class.
Hope this help.
EDIT 1
Update filter according to dimyG's answer
Add django-widget-tweak link
EDIT 2