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

2024-06-16 12:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

 # -*- 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'

文件中的标记工作良好,但过滤器不工作。但我不知道为什么。。。


Tags: registertruedefhtmltagcreatecontexttemplate
2条回答

要在django中创建自定义过滤器,请执行以下步骤

1)。在应用程序中创建一个模板标签文件夹。

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

(第三章)。添加您的自定义过滤器名称。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__

(四)。若要加载此筛选器,请在顶部添加此 {%加载您的自定义筛选名称%} 在html模板中。

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

有关更多信息,请点击此链接https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/

一。您是否将包含筛选器的文件放在应用程序的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 %}

在你的模板中。

相关问题 更多 >