Easy Django form customization using django-widget-tweaks

When customizing Django forms, you usually have to add it on the forms definition using the widget. Say for example you want to add a class attribute to a form input. You have to do it this way

forms.py :

While this method of adding attributes to a form instance can be easily performed, it can get quite cumbersome if different developers are working on the project (example: developer and designer).

To solve this, you can use django-widget-tweaks, it’s a lightweight application that allows developers to tweak template rendering of Django forms. By using django-widget-tweaks, there’s absolutely no need to alter python level definitions of the forms. So designers can do template customization without altering the python code. The app provides template filters that can alter CSS attributes of Django form fields.

Installation:

  1. pip install django-widget-tweaks
  2. add ‘widget_tweaks’ to INSTALLED_APPS.

Below are some examples of the template filters:

add_class : Adds CSS classes to a field, separate classes with whitespace to append multiple classes at

once.

attr : Adds or replaces an html attribute for a form field.

set_data : Sets HTML5 data attribute. This method is a shortcut for the ‘attr’ filter that prepends the attribute names with ‘data-’ string.

Documentation : http://pypi.python.org/pypi/django-widget-tweaks