Django could not load template tag

最后都变了- 提交于 2019-12-07 17:54:11

问题


I have created a templatetags folder inside my application and inside a file named posts.py, I have written the following code;

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) 

Now, I try to load this template tag inside my template;

{% load get_all_posts %}

But this gives me with error, '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

What is the error in this template or have I missed something here.


回答1:


With load you need to use the name of the library, not the tag - so posts in your case.

(I assume you also have a blank __init__.py in the templatetags directory, and that the application is in INSTALLED_APPS).




回答2:


suppose you have the following structure:

-- Application_Name

-------templatetags

--------------__init__.py

--------------templates_extras.py

-------__init__.py

-------settings.py

-- manage.py

You have to make sure of the following:

  • your application itself inside which your "templatetags" is resident is actually installed in INSTALLED_APPS in settings.py (e.g. "Application_Name")

  • your tag module itself that exists inside "templatetags" is already installed in INSTALLED_APP in settings.py (e.g. "ApplicationName.templatetags.tempaltes_extras")

  • keep sure you have "__init__.py" under templatetags directory

  • you have to restart the server

  • In some cases you have to remove all generated *.pyc if it did not work then retry again



来源:https://stackoverflow.com/questions/8607544/django-could-not-load-template-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!