How to properly make custom filter in django framework?

kspacja picture kspacja · Feb 8, 2011 · Viewed 13.9k times · Source
 # -*- coding: utf-8 -*-
from django import template
register = template.Library()

@register.inclusion_tag('menu/create_minimenu.html', takes_context = True)
def minimenu(context):
....
....
@register.inclusion_tag('menu/create_topmenu.html', takes_context = True)
def topmenu(context):
....
....
@register.filter(name = 'commatodot')
def commatodot(value, arg):
    return str(value).replace(",", '.')
commatodot.isSafe = True

template.html

...
initGeolocation2({{ place.longitude|commatodot }}, {{ place.latitude|commatodot }}, "MAIN");
...

Error:

TemplateSyntaxError at /places/3/

Invalid filter: 'commatodot'

Request Method:     GET
Request URL:    http://localhost:8000/places/3/
Django Version:     1.2.4
Exception Type:     TemplateSyntaxError
Exception Value:    

Invalid filter: 'commatodot'

This tags from file work well, but the filter not. But I don't know why...

Answer

mipadi picture mipadi · Feb 8, 2011

1. Did you put the file with the filters inside a templatetags module in your app? I.e., you should have a structure like:

project/
  my_app/
    templatetags/
      __init__.py    # Important! It makes templatetags a module. You can put your filters here, or in another file.
      apptags.py     # Or just put them in __init__.py

2. Did you include the tags? You need something like

{% load apptags %}

in your template.