Thursday, January 31, 2013

Adding css class to a django form field in a template

One way of adding a css class to a Django form field in template is to create a widget for each of the form fields. But It is often annoying to define each field in the ModelForm again just to use widget. There is another way of doing this without creating widgets. All you need to do is to use an app called "widget_tweaks". You can install it using this command:
pip install django-widget-tweaks
Then add 'widget_tweaks' to INSTALLED_APPS of your Django project. To use it in your template, load the app in your template first:
{% load widget_tweaks %}
To add a css class to a form field, use the 'add_class' template filter.
{{ form.title|add_class:"css_class_1" }}
Multiple css classes can also be added.
{{ form.title|add_class:"css_class_1 css_class_2 css_class_3" }}
This app also provides several template filters that can alter CSS classes and HTML attributes of Django form fields. Details can be found here.

No comments:

Post a Comment