2016-11-18 34 views
13

我想要一個菜單​​,它可以自定義您所屬的組。 我使用Django 1.10.1,allauth等等。 當我嘗試讓我的templatetag失敗,它說:¨Django 1.10.1'my_templatetag'不是已註冊的標籤庫。必須是以下之一:

TemplateSyntaxError at/
'my_templatetag' is not a registered tag library. Must be one of: 
account 
account_tags 
admin_list 
admin_modify 
admin_static 
admin_urls 
cache 
i18n 
l10n 
log 
socialaccount 
socialaccount_tags 
static 
staticfiles 
tz 

'my_templatetag.py' 看起來是這樣的:

from django import template 
from django.contrib.auth.models import Group 


register = template.Library() 

@register.filter(name='has_group') 
def has_group(user, group_name): 
    group = Group.objects.get(name=group_name) 
    return group in user.groups.all() 

和Tha錯誤出現在我的.html文件,該文件說,

{% load my_templatetag %} 

我試圖重啓像數百萬次的服務器,還我試圖改變所有的名字,而應用程序是INSTALLED_APPS的settings.py中的一部分。 我在做什麼錯?

回答

23

除了在app_name/templatetags內放置my_templatetag.py之外,請確保每次修改模板標記時重新啓動Django開發服務器(或確保它自己重新啓動)。如果服務器不重新啓動,Django將不會註冊標籤。

11

從Django的1.9,你可以加載在設置這些新的標籤/過濾器是這樣的:

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [], 
    'APP_DIRS': True, 
    'OPTIONS': { 
     'context_processors': [ 
      'django.template.context_processors.debug', 
      'django.template.context_processors.request', 
      'django.contrib.auth.context_processors.auth', 
      'django.contrib.messages.context_processors.messages', 
      'app.apptemplates.load_setting', 

     ], 

     'libraries':{ 
      'my_templatetag': 'app.templatetags.my_templatetag', 

      } 
    }, 
}, 

]

+0

非常感謝:)無法讓它以另一種方式工作。 – Jonathan

+0

謝謝,它爲我工作! – RockOnGom

+0

它也適用於我。這可能實際上是這個問題的選擇答案。如果人們想知道,我正在使用django的2.0版本。 – Doug

0

我知道這是有點老了,但我今天遇到了同樣的問題。我發現在文檔的解決方案:https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/

的應用程序應該包含創建一個templatetags目錄,在同級別的models.py,views.py等。如果這不存在,創建它 - 唐忘記__init__.py文件以確保該目錄被視爲Python包。

只需將__init__.py從其他位置複製到新的templatetag的目錄中就可以對其進行整理。

1

重新啓動django服務器。它在templatetag文件夾中的應用程序和template_name.py中設置了templatetag文件夾之後爲我工作。

5

確保您不會錯過任何步驟如下:

  1. 創建一個在同一水平稱爲「templatetags」爲models.py 和views.py在你的應用程序文件夾文件夾

  2. 您的應用程序必須在INSTALLED_APPS settings.py中

  3. 的templatetags文件夾必須__init__。PY

  4. 重新啓動Django的服務器

+0

在我看來,我所有的應用程序都需要一個apps.py和__init__.py來包含'default_app_config ='custom_admin.apps.Config''。否則,Django 1.10不會加載模板標籤。儘管我沒有在文檔中明確地看到這一點。 – felix

0

放my_templatetag.py內APP_NAME/templatetags然後創建初始化內部APP_NAME的.py/templatetags ..項目文件夾然後打開終端給出命令python manage.py從app_name.templatetags進口my_templatetag殼

+0

內部templatetags文件夾條目空白文件的名稱__init__.py –

+0

請[編輯您的答案](https://stackoverflow.com/posts/47772135/edit)將所有細節放入它並格式化爲可讀(使用代碼格式在適當情況下)。 – Melebius

0

你剛纔剪切/刪除你的代碼的(例如templatetags/home.py)裏面寫 從home.py您刪除代碼,並重新啓動服務器,並再次粘貼home.py它會用自己的代碼。

相關問題