Login

Custom CSS class in Form with template tag filter

Author:
kegan
Posted:
June 23, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

A lot of times we need to insert a specific CSS class into a Form instance for it to be rendered in the template.

The current method is to specify the CSS class in the Python code through the form field widget. But it would be easier for the designer to be able to specify the CSS class in the template directly.

For example rather than doing this in your Python code:

'name = forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))`

You can do this in your template:

{{ form.name|cssclass:"special"}}

This template filter only works with Form Field instance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re
from django import template


register = template.Library()
CLASS_PATTERN = re.compile(r'\bclass="[\w\d]*"')

def cssclass(value, arg):
    """
    Replace the attribute css class for Field 'value' with 'arg'.
    """
    attrs = value.field.widget.attrs
    orig = attrs['class'] if 'class' in attrs else None

    attrs['class'] = arg
    rendered = str(value)

    if orig:
        attrs['class']
    else:
        del attrs['class']

    return rendered
register.filter('cssclass', cssclass)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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

Please login first before commenting.