【问题标题】:Django could not load template tagDjango 无法加载模板标签
【发布时间】:2012-01-26 07:28:02
【问题描述】:

我在我的应用程序和一个名为posts.py 的文件中创建了一个templatetags 文件夹,我编写了以下代码;

from django.template import Library, Node
from advancedviews.models import Post
register = Library()
class AllPost(Node):
    def render(self,context):
        context['all_posts'] =  Post.objects.all()
        return ''
def get_all_posts(parser,token):
    return AllPost()
get_all_posts = register.tag(get_all_posts) 

现在,我尝试在我的模板中加载这个模板标签;

{% load get_all_posts %}

但这给了我错误,'get_all_posts' is not a valid tag library: Template library get_all_posts not found, tried django.templatetags.get_all_posts,django.contrib.admin.templatetags.get_all_posts

这个模板有什么错误或者我在这里遗漏了什么。

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    对于load,您需要使用库的名称,而不是标签 - 所以posts 在您的情况下。

    (我假设您在 templatetags 目录中也有一个空白的 __init__.py,并且应用程序在 INSTALLED_APPS 中)。

    【讨论】:

    • 好吧,我编辑了上面的代码,但它仍然给了我同样的错误。
    • 我发现我的错误,我只是加载了错误名称的文件。现在,我成功地将标签加载为 {% load posts %},然后将函数加载为 {% get_all_posts %}。现在,我可以使用所有上下文变量。是这样的吗?
    【解决方案2】:

    假设你有以下结构:

    -- Application_Name
    
    -------templatetags
    
    --------------__init__.py
    
    --------------templates_extras.py
    
    -------__init__.py
    
    -------settings.py
    
    -- manage.py
    

    您必须确保以下几点:

    • 您的“模板标签”所在的应用程序本身实际上安装在 settings.py 的 INSTALLED_APPS 中(例如“Application_Name”)

    • 存在于“templatetags”中的标签模块本身已经安装在 INSTALLED_APP 的 settings.py 中(例如“ApplicationName.templatetags.tempaltes_extras”)

    • 确保您在 templatetags 目录下有“__init__.py

    • 你必须重启服务器

    • 在某些情况下,您必须删除所有生成的 *.pyc,如果它不起作用,然后重试

    【讨论】:

    • 删除旧的*.pyc 文件解决了我的问题。谢谢!
    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 2015-11-10
    • 2021-04-08
    • 2010-11-15
    • 2013-04-22
    • 2011-12-11
    • 2016-02-25
    • 1970-01-01
    相关资源
    最近更新 更多