Login

Type checking templatetag filters

Author:
marcorogers
Posted:
February 25, 2010
Language:
Python
Version:
1.1
Tags:
templatetags
Score:
0 (after 2 ratings)

It's often useful to be able to check the type of an object in templates. Most recently I used this to do some trickery in my forms for certain field types. These template filters allow you to match the type of an object or a field widget with a string. It returns True if it matches and False if it doesn't or there is an error.

for example:

{% if form|obj_type:'mycustomform' %} <form class="custom" action=""> {% else %} <form action=""> {% endif %}

{% if field|field_type:'checkboxinput' %} <label class="cb_label">{{ field }} {{ field.label }}</label> {% else %} <label for="id_{{ field.name }}">{{ field.label }}</label> {{ field }} {% endif %}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
filters for checking the type of objects and formfields

Usage:

{% if form|obj_type:'mycustomform' %}
  <form class="custom" action="">
{% else %}
  <form action="">
{% endif %}


{% if field|field_type:'checkboxinput' %}
  <label class="cb_label">{{ field }} {{ field.label }}</label>
{% else %}
  <label for="id_{{ field.name }}">{{ field.label }}</label> {{ field }}
{% endif %}

"""

from django import template
register = template.Library()

def check_type(obj, stype):
    try:
        t = obj.__class__.__name__
        print t
        return t.lower() == str(stype).lower()
    except:
        pass
    return False
register.filter('obj_type', check_type)

def field_type(field, ftype):
    return check_type(field.field.widget, ftype)
register.filter('field_type', field_type)

More like this

  1. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 7 months ago
  2. load m2m fields objects by dirol 4 years, 11 months ago
  3. Multiple-Submit-Button Widget for Choice Field by Archatas 6 years, 9 months ago
  4. Generic model filter from request GET data by genbit 3 years, 9 months ago
  5. Generic CSV Export by zbyte64 6 years, 11 months ago

Comments

Tomek (on November 8, 2010):

Line 27 - there should not be print t inside template filter - or it will alway return false due to exception that i thrown when using this filter in template. So please remove it or comment it in your code.

#

Please login first before commenting.