Cannot register custom filters - Template thinks they are invalid

26 views
Skip to first unread message

Salim Fadhley

unread,
Apr 18, 2008, 8:18:28 AM4/18/08
to Django users
I want to define the simplest possible filter and then invoke it from
my simplest possible template, however I am beset by some problems:

I'm defining filters thus - this code is at the top of the same .py
file as where I invoke the register_to_string method.

@register.filter
@stringfilter
def tf( val ):
return "ABC"

But when I try to invoke the filter using the 'render_to_string'
shortcut I get this error:

Exception Type: TemplateSyntaxError
Exception Value: Invalid filter: 'tf'

But when I inspect the library object in PDB it appears that all is
well:

(Pdb) register
<django.template.Library object at 0x01AAB930>
(Pdb) register.filters
{'tf': <function tf at 0x01AB03F0>, 'render_object_to_string':
<function render_object_to_string at 0x01AB04B0>, 'e
repr': <function erepr at 0x01AB0470>}
(Pdb) c

Is there some extra trick I need to do in order to make my additional
filters work with the render_to_string shortcut?

THANKS

Malcolm Tredinnick

unread,
Apr 18, 2008, 8:28:21 AM4/18/08
to django...@googlegroups.com

On Fri, 2008-04-18 at 05:18 -0700, Salim Fadhley wrote:
> I want to define the simplest possible filter and then invoke it from
> my simplest possible template, however I am beset by some problems:
>
> I'm defining filters thus - this code is at the top of the same .py
> file as where I invoke the register_to_string method.

This isn't the normal way to create a filter. Filters are defined in
files that live inside the templatetags/ directory of an application.
What you are doing may or may not work, but if it works, it's more or
less by accident.

>
> @register.filter
> @stringfilter
> def tf( val ):
> return "ABC"
>
> But when I try to invoke the filter using the 'render_to_string'
> shortcut I get this error:
>
> Exception Type: TemplateSyntaxError
> Exception Value: Invalid filter: 'tf'

I would guess that this means you haven't loaded the templatetag file
into the template. Fix the filter creation so that it's done in the
normal way (in a file in templatetags/) and, if you are still having
trouble, post the template you are trying to use it in.

Regards,
Malcolm

--
A clear conscience is usually the sign of a bad memory.
http://www.pointy-stick.com/blog/

Reply all
Reply to author
Forward
0 new messages