How to add additional classes to django form field
css, django, django-templates, forms
Solution
I figured out how to do it using a custom BoundField
from django.forms import forms
class CustomBoundField(forms.BoundField):
def css_classes(self, extra_classes=None):
# logic for determining css_classes has been omitted
extra_classes = ['name', 'text']
return super(CustomBoundField, self).css_classes(extra_classes=extra_classes)
In my forms, I overide getitem
def __getitem__(self, name):
try:
field = self.fields[name]
except KeyError:
raise KeyError('Key %r not found in Form' % name)
return CustomBoundField(self, field, name)
Problem
I've just recently learned about: ``` Form.error_css_class Form.required_css_class ``` Docs: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.error_css_class So by defining 'error_css_class' and 'required_css_class' in forms ``` class MyForm(forms.Form): error_css_class = 'error' required_css_class = 'required' name = forms.CharField(...) ``` I can do: ``` <div class="field-wrapper {{ form.name.css_classes }}"> ... </div> ``` This will output: ``` <div class="field-wrapper required"> ... </div> ``` However I want to add additional classes to the field, e.g I would like to add 'text name' css class for the "name" field. And reading the docs, I think its possible. https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.BoundField.css_classes After reading the above I tried to do ``` self.fields['name'].css_classes('name text') ``` That doesn't work. I get ``` 'CharField' object has no attribute 'css_classes' ``` I also tried ``` name = forms.CharField(css_classes='name text') ``` TypeError ``` __init__() got an unexpected keyword argument 'css_classes' ``` I know I can add extra attr to field widget ``` self.fields['name'].widget.attrs['class'] = 'name text' ``` But I want to add css classes to field wrapper. I could write a custom templatetag... to check field name/type and return appropriate css classes... but if there is something builtin .. I would love to keep my templates clean :-). Also hardcoding css classes per field is not an option .. as the form fields are dynamic. Any help will be appreciated.