<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=338168267432629&amp;ev=PageView&amp;noscript=1">

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 : from django import forms class VolunteerForm(forms.Form) name = forms.TextInput() address =forms.TextField(widget=forms.Textarea(attrs={‘class’:’volunteer_class’})) …


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 :

from django import forms
class VolunteerForm(forms.Form)
name = forms.TextInput()
address =forms.TextField(widget=forms.Textarea(attrs={'class':'volunteer_class'}))

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.

<!---add 2 class to form field : inputContact volunteer-->

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

<!--add new attribute name-->


<!--add multiple attributes-->


<!---add attributes without parameter->

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

<!--data-filters:"Overtext" will be added to the input field-->

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

Similar posts

Get notified about the latest in Tech

Be the first to know about new tech from the experts at Bixly!