Login

Type checking templatetag filters

Author:
marcorogers
Posted:
February 25, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.