2013-10-20 81 views
2

我很抱歉再次提出這個問題,但我嘗試了幾種來自堆棧溢出和一些教程的解決方案,但我還是無法創建自定義模板標籤。當我嘗試通過python manage.py runserver嘗試啓動服務器時,我得到的是ImportError: No module named test_tagDjango:創建自定義模板標籤 - > ImportError

我創建了一個非常基本的模板標籤(這裏找到:django templatetag?),像這樣:

我的文件夾結構:

demo 
    manage.py 
    test 
     __init__.py 
     settings.py 
     urls.py 
     ... 
     templatetags 
      __init__.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:

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

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

,我的settings.py:

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

請讓我知道,如果你從我的settings.py和我做錯了什麼,所以我不能甚至開始我的服務器需要更多的信息。 (如果我從已安裝的應用程序中刪除'test_tag',我可以啓動服務器,但當我遇到test_tag未知的錯誤時)。

由於

回答

4

templatetags文件夾應該是在應用程序內。

你的項目樹應該是這個樣子:

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 

然後,添加test_appINSTALLED_APPS,並從那裏取出test_tag

+0

現在我得到'ImportError:No module named test_app'。 –

+0

@AlexanderScholz該應用程序應該有標準的「應用程序結構」,請參閱更新的答案。 –

+0

Aahh我終於明白了:)非常感謝。我認爲「測試」已經是一個應用程序(我對django非常陌生)。我可以省略'models.py','views.py'和'tests.py',它可以工作。 –

相關問題