Login

Custom CSS class in Form with template tag filter

Author:
fernandogrd
Posted:
October 18, 2011
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

It was based in: http://djangosnippets.org/snippets/1586/

Instead of doing this: 'attribute_name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))`

You can do this in your template:

{{ form|cssclass:"attribute_name:special_class"|cssclass:"other_attribute:special_class" }}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# -*- coding:utf-8 -*-
from django import template

register = template.Library()


@register.filter
def cssclass(form, name_arg):
    """
    Replace the attribute css class for Field 'name' with 'arg'.
    name_args expects format: "attribute_name:special_class"
    """
    name, arg = name_arg.split(':')
    form.fields[name].widget.attrs['class'] = arg

    return form

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

fernandogrd (on October 19, 2011):

ws, very interesting features in django-widget-tweaks, but it applies only to fields, this one applies for form itself.

#

Please login first before commenting.