Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django can't find my custom template filter

I'm trying to create a custom template filter in my Django app. I've created a templatetags folder under my app, added an __init__.py file and a filters.py file with my filters, like so:

import os
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def filename(pathname):
    """ Returns the file's name, without folder """
    return os.path.basename(pathname)

When I try to access the filter from a template, I get the error "Invalid filter 'filename'"

This question has been asked a lot, so I already checked the following:

  • __init__.py is properly named
  • After opening a shell with manage.py shell I can import my filter like so: import app.templatetags
  • I can also use the filter properly from the Django shell
  • I have restarted the Django development server.
  • I have placed a breakpoint on the call to template.library() - the debugger doesn't stop there.

Here is the template (I've removed parts of it, but the error persists in this small version, as well)

<form enctype="multipart/form-data" action="{% url lab.views.new.artefact_drop_web tempfile_id=tempfile.id %}" method="post"> 
    {% csrf_token %} 
    <h3>File:</h3>
    <p>{{ tempfile.file.name|filename }}</p>
    <input type="submit" value="Add" />
</form>
like image 238
zmbq Avatar asked Dec 16 '22 12:12

zmbq


1 Answers

You need to use {% load name_of_file_tags_are_in %} inside your template.

https://docs.djangoproject.com/en/1.5/howto/custom-template-tags/

like image 84
Ngenator Avatar answered Dec 18 '22 11:12

Ngenator