【问题标题】:How to properly make custom filter in django framework?如何在 django 框架中正确制作自定义过滤器?
【发布时间】:2011-06-23 17:22:33
【问题描述】:
 # -*- coding: utf-8 -*-
from django import template
register = template.Library()

@register.inclusion_tag('menu/create_minimenu.html', takes_context = True)
def minimenu(context):
....
....
@register.inclusion_tag('menu/create_topmenu.html', takes_context = True)
def topmenu(context):
....
....
@register.filter(name = 'commatodot')
def commatodot(value, arg):
    return str(value).replace(",", '.')
commatodot.isSafe = True

模板.html

...
initGeolocation2({{ place.longitude|commatodot }}, {{ place.latitude|commatodot }}, "MAIN");
...

错误:

TemplateSyntaxError at /places/3/

Invalid filter: 'commatodot'

Request Method:     GET
Request URL:    http://localhost:8000/places/3/
Django Version:     1.2.4
Exception Type:     TemplateSyntaxError
Exception Value:    

Invalid filter: 'commatodot'

文件中的这个标签效果很好,但过滤器不行。但我不知道为什么...

【问题讨论】:

    标签: python django django-template-filters


    【解决方案1】:

    1。您是否将带有过滤器的文件放在应用程序的 templatetags 模块中?即,您应该具有如下结构:

    project/
      my_app/
        templatetags/
          __init__.py    # Important! It makes templatetags a module. You can put your filters here, or in another file.
          apptags.py     # Or just put them in __init__.py
    

    2。你包括标签了吗?你需要类似的东西

    {% load apptags %}
    

    在您的模板中。

    【讨论】:

    • 完成了...还有模板标签和“包含”。但不能解决我的问题以及我编写自定义标签的工作方式。
    • 你不是include标签库,你load它:{% load apptags %}
    • @mipadi 感谢templatetags 提示。但是我一直收到相同的错误消息,在我看来,Django 并没有在寻找 my_app.templatetags,尽管我的 myapp 已在 INSTALLED_APPS 中列出。你有什么建议?谢谢
    • @DiAlex 提示很重要。在 settings.py 中将应用位置添加到 INSTALLED_APPS
    【解决方案2】:

    要在 django 中创建自定义过滤器,请按照以下步骤操作

    1)。在您的应用中创建 template_tags 文件夹

    2)。在此文件夹中添加/复制__init__.py 文件,以确保这是一个 python 文件夹。

    3)。添加 your_custom_filter_name.py 文件看起来像:

    from django import template register = template.Library()

    @register.filter(name = 'get_class') '''A filter for get class name of object.''' def get_class(value): return value.__class__.__name__

    4)。要加载此过滤器,请在顶部添加 {% 加载 your_custom_filter_name %} 在 html 模板中。
    .

    5)。 重新启动您的服务器并享受 :)

    对于更多信息https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/点击此链接

    【讨论】:

    • 看起来文件名必须是 custom_filter ,我们无法将其更改为我们想要的任何内容。我们可以吗?
    • 你可以改变它,对不起:)。
    • 我之前没有重启服务器。你是对的,它奏效了。谢谢!
    • 重启服务器这句话很重要,这个错误快把我逼疯了。
    • s/template_tags/templatetags/
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2015-12-08
    • 2015-01-23
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多