简体   繁体   English

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

[英]How to properly make custom filter in django framework?

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

template.html template.html

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

Error: 错误:

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'

This tags from file work well, but the filter not. 来自文件的这个标签运行良好,但过滤器没有。 But I don't know why... 但我不知道为什么......

1. Did you put the file with the filters inside a templatetags module in your app? 1.您是否将带有过滤器的文件放在应用程序的templatetags模块中? Ie, you should have a structure like: 即,你应该有一个像这样的结构:

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. Did you include the tags? 你有标签吗? You need something like 你需要类似的东西

{% load apptags %}

in your template. 在你的模板中。

For create your custom filter in django follow these steps 要在django中创建自定义过滤器,请按照下列步骤操作

1). 1)。 Create a template_tags folder in your app. 在您的应用中创建template_tags文件夹

2). 2)。 Add/Copy a __init__.py file in this folder for ensure that this is a python folder. 在此文件夹中添加/复制__init__.py文件,以确保这是一个python文件夹。

3). 3)。 Add your_custom_filter_name.py file look like: 添加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). 4)。 To load this filter add this at top {% load your_custom_filter_name %} in html template . 要加载此过滤器,请在html模板中将{%load your_custom_filter_name%}添加到顶部。
.

5). 5)。 Restart your server and enjoy :) 重启你的服务器 ,享受:)

And for more info https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/ follow this link 有关更多信息, 请访问https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/点击此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM