我正在尝试在我的 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
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>
最佳答案
您需要在模板中使用 {% load name_of_file_tags_are_in %}
。
https://docs.djangoproject.com/en/1.5/howto/custom-template-tags/
关于python - Django 找不到我的自定义模板过滤器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15806254/