Search code examples
djangodjango-template-filters

django: Invalid filter


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

Solution

  • 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/