Question

I have a python file in my Django project which contains a custom template tag and a custom template filter.

My custom tag uses template.loader.get_template() to load another template file. This worked great... until I added my custom filter to the loaded template.

Now I get a Django "Invalid Filter" TemplateSyntaxError exception. Looking at the call stack, Django is unable to load my template filter.

Here's where things get weird. I can use my custom filters from another template. I can use any other filter inside the template loaded by my custom tag. But I can't use my own filter inside my own custom tag.

The obvious cause of this would be not loading my custom tag/filter file inside my template HTML, but I am correctly loading it. (because when I don't load it, I'll get a different error -- "invalid block tag")

I'm running Django 1.2.3 on Python 2.7.

[BTW, I finally found the answer myself, but it took me several hours and I wasn't able to find the answer anywhere on stackoverflow or google, so I'm going to answer my own question so others won't have to waste as much time as I did]

Was it helpful?

Solution

The answer is maddeningly simple: split the custom tag and custom filter into two separate python files and it will work.

I suspect the problem is this: the custom tag is using template.loader.get_template() to load another template. That template file contains a {% load %} tag which tries to load the same file in which the parent custom tag is defined. For some reason, this doesn't work-- perhaps because it would cause an infinite loop or because Django assumes it's already loaded.

I didn't try recusrively loading a custom tag inside a filter, or a tag inside another tag, to see if the same problem occurs there too, but if it does, the fix would be the same: if you want to use template.loader.get_template() to load a template which contains calls to your own custom tags or filters, make sure that the file calling template.loader.get_template() is a different file from the file defining your included tags/filers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top