简体   繁体   English

Django:创建自定义模板标签-> ImportError

[英]Django: Create custom template tag -> ImportError

I'm sorry to ask this again, but I tried several solutions from stack overflow and some tutorials and I couldn't create a custom template tag yet. 很抱歉再次问到这个问题,但是我尝试了堆栈溢出的一些解决方案和一些教程,但还无法创建自定义模板标签。 All I get is ImportError: No module named test_tag when I try to start the server via python manage.py runserver . 我得到的只是ImportError: No module named test_tag当我尝试通过python manage.py runserver启动服务器时, ImportError: No module named test_tag

I created a very basic template tag (found here: django templatetag? ) like so: 我创建了一个非常基本的模板标记(在这里找到: django templatetag? ),如下所示:

My folder structure: 我的文件夹结构:

demo
    manage.py
    test
        __init__.py
        settings.py
        urls.py
        ...
        templatetags
            __init__.py
            test_tag.py

test_tag.py: test_tag.py:

from django import template
register = template.Library()

@register.simple_tag
def test_tag(input):
    if "foo" == input:
        return "foo"
    if "bar" == input:
        return "bar"
    if "baz" == input:
        return "baz"
    return ""

index.html: index.html的:

{% load test_tag %}
<html>
    <head>
    ...
    </head>
    <body>
        {% cms_toolbar %}

        {% foobarbaz "bar" %}
        {% foobarbaz "elephant" %}
        {% foobarbaz "foo" %}
    </body>
</html>

and my settings.py: 和我的settings.py:

INSTALLED_APPS = (
    ...
    'test_tag',
    ...
)

Please let me know if you need further information from my settings.py and what I did wrong so I can't even start my server. 如果您需要我settings.py中的更多信息以及我做错了什么,请甚至告诉我,我什至无法启动服务器。 (If I delete 'test_tag' from installed apps I can start the server but I get the error that test_tag is not known, of course). (如果我从已安装的应用程序中删除“ test_tag”,则可以启动服务器,但是我得到的错误是,当然不知道test_tag)。

Thanks 谢谢

The templatetags folder should be within an application. templatetags文件夹应位于应用程序内。

You project tree should look something like: 您的项目树应类似于:

demo
    manage.py
    test
        __init__.py
        settings.py
        urls.py
    test_app
        __init__.py
        models.py
        tests.py
        views.py
        templatetags
            __init__.py
            test_tag.py

Then, add test_app to INSTALLED_APPS , and remove test_tag from there. 然后,将test_app添加到INSTALLED_APPS ,然后从其中删除test_tag

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

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