I got an article app and trying to make a custom filter, I have a directory called templatetags in article app, and a tags.py within that directory, here is the directory structure.
-manage.py(f)
-settings.py(f)
-articles(d)
- templatetags(d)
- tags.py(f)
On the templates, the articles have its own directory, all article templates extend from a base.html template, here is the template structure.
-base.html(f)
-articles(d)
-index.html(f)
I load the tags in base.html {% load tags %} and use the custom filter in index.html and got the invalid filter error.
tags.py
from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
@stringfilter
def space2Dash(s):
return s.replace(' ', '_');
I just can't figure out what I did wrong.
edit:
I changed the filter name to abcfilter.py
and I have the article app loaded in my settings.py
articles/index.html
{% load abcfilter %}
{{ "foo bar"|space2dash }}
the error:
Request Method: GET
Request URL: http://localhost:8080/articles/
Django Version: 1.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'space2dash'
Exception Location: ***/lib/python2.7/django/template/__init__.py in find_filter, line 363
Python Executable: /usr/local/bin/python
Python Version: 2.7.1
Server time: Sun, 10 Apr 2011 07:55:54 -0500
Just for reference, I solved the problem by moving
{% load ... %}
from the base template to the concrete template. See also this post https://stackoverflow.com/a/10427321/3198502
First off remove the semicolon after your replace.
Do you have a file called __init__.py
(this is suppose to have 2 underscores before and after init, hard to format in editor.) under the templatetags directory?
Here is a good page with lots of info if you haven't looked yet.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I was nearly going nuts with this problem and none of the above answers helped.
If you have several apps, make sure that the file names containing your custom tags/filters are unique, prefereablyapp_name_filters.py
. Otherwise Django will only load the custom filters from the app it finds matching first!
To avoid loading the module in each template using {% load MODULE_NAME %}
, you can add it as a 'builtin'
in settings.py
:
TEMPLATES = [
{
'OPTIONS': {
...
,
'builtins': [
...
'APP_NAME.templatetags.MODULE_NAME',
]
},
},
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With