Type checking templatetag filters

 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. NewForms Readonly / Edit Pattern by FreddieP 5 years, 6 months ago
  2. FieldAccessForm (per-field user access for forms derived from models) by Killarny 4 years, 8 months ago
  3. caching parsed templates by forgems 5 years, 6 months ago
  4. Radio widget with labels after inputs by avsd 11 months, 2 weeks ago
  5. load m2m fields objects by dirol 3 years 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.

#

Tomek (on November 22, 2010):

Today I found other filter which You might like more:

http://djangosnippets.org/snippets/294/

#

(Forgotten your password?)