django写我的第一个自定义模板标签和过滤器

时间:2014-10-07 23:50:24

标签: python django replace django-templates

我正在尝试编写一个简单的django Custom template tags and filters来用模板上的行空格替换html break(< b r />)。

我已经关注了django文档,但是我收到了以下错误,我不知道如何解决。

我遇到的错误是:

x_templates_extra' is not a valid tag library: Template library x_templates_extra not found, tried django.templatetags.x_templates_extra,django.contrib.staticfiles.templatetags.x_templates_extra,django.contrib.admin.templatetags.x_templates_extra,django.contrib.flatpages.templatetags.x_templates_extra,rosetta.templatetags.x_templates_extra,templatetag_handlebars.templatetags.x_templates_extra,globalx.common.templatetags.x_templates_extra,rollyourown.seo.templatetags.x_templates_extra,debug_toolbar.templatetags.x_templates_extra

这就是我所做的:

1. created a templatetags directory, at the same level as models.py, views.py, etc

2. created a __init__.py file inside the templatetags directory to ensure the directory is treated as a Python package

3. created a file inside the templatetags directory called x_templates_extra.py

4. added the load tag to the template: {% load x_templates_extra %}

5. added the tag to the template: {{ x_detail.x_details_institution_name|safe|replace:"<br />"|striptags|truncatechars:popover_string_length_20 }}

6. Added the following code to the file x_templates_extra.py:

from django import template

register = template.Library()

def replace(value, arg):
   """Replaces all values of arg from the given string with a space."""
    return value.replace(arg, ' ')

问题:

文档声明:因此,在模块顶部附近,请输入以下内容:

from django import template

register = template.Library()

我把导入&amp;在我的文件中注册名为:x_templates_extra.py的行。这是对的吗?

此外,我不确定在INSTALLED_APPS中放入什么来使负载正常工作。

尝试了很多事情,但我现在正在圈子里,所以我确实需要帮助。

感谢。

2 个答案:

答案 0 :(得分:1)

最后让它发挥作用。

将正确的应用名称添加到已安装的应用程序名称中。

答案 1 :(得分:0)

如果您的应用名称为foo且您的代码文件夹名称为goo,那么您应该在settings.py中拥有:

INSTALLED_APPS = [
'foo',
'foo.goo'

您的应用包下的apptag folder 那里需要Django项目。

-> foo
    ---> models.py
    ---> views.py
    ---> goo
      -----> __init__.py
      -----> app_filters.py