4

我正在尝试在我的 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我可以像这样导入我的过滤器: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>
4

1 回答 1

12

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

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

于 2013-04-04T08:48:44.800 回答