如何在Django框架中正确制作自定义过滤器?

4 投票
2 回答
14484 浏览
提问于 2025-04-16 11:28
 # -*- 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'

这个文件里的标签工作得很好,但过滤器却不行。我不知道为什么...

2 个回答

9

要在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') '''一个用于获取对象类名的过滤器。''' def get_class(value): return value.__class__.__name__

4). 要加载这个过滤器,在HTML模板的顶部添加{% load your_custom_filter_name %}

5). 重启你的服务器,然后享受吧 :)

想要了解更多信息,可以访问这个链接 https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/

26

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

撰写回答