Django找不到我的自定义模板过滤器

时间:2013-04-04 08:35:30

标签: python django filter django-templates

我正在尝试在我的Django应用中创建自定义模板过滤器。我在我的应用程序下创建了一个templatetags文件夹,在我的过滤器中添加了__init__.py文件和filters.py文件,如下所示:

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)

当我尝试从模板访问过滤器时,出现错误“无效过滤器'文件名'”

这个问题已经被问了很多,所以我已经检查了以下内容:

  • __init__.py已正确命名
  • 使用manage.py shell打开shell后,我可以像这样导入我的过滤器:import app.templatetags
  • 我也可以从Django shell中正确使用过滤器
  • 我重新启动了Django开发服务器。
  • 我在调用template.library()时设置了断点 - 调试器不会就此停止。

这是模板(我删除了部分模板,但错误仍然存​​在于这个小版本中)

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

1 个答案:

答案 0 :(得分:11)

您需要在模板中使用{% load name_of_file_tags_are_in %}

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