Django 1.10.1 'my_templatetag' is not a re

2020-02-08 05:06发布

I want a menu thats custom depending which group you are member of. Im using Django 1.10.1, allauth and so on. When im trying to make my templatetag it fails and it says:¨

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' looks like this:

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()

and tha error comes in my .html file which say,

{%  load my_templatetag %}

I have tried to restart the server like millions of times, also i tried to change all the names, and the app is a part of INSTALLED_APPS in settings.py. What am I doing wrong?

11条回答
聊天终结者
2楼-- · 2020-02-08 05:28

Make sure you are not missing any of the following steps:

  1. Create a folder called "templatetags" at the same level as models.py and views.py in your application folder

  2. Your application must be in the INSTALLED_APPS in settings.py

  3. The templatetags folder must have __init__.py

  4. Restart the django server

查看更多
男人必须洒脱
3楼-- · 2020-02-08 05:30

In my case the problem was, I was using {% load filter_method_name %}

I had to change to {% load filename %}

I then had to restart the server.

查看更多
We Are One
4楼-- · 2020-02-08 05:34

Besides putting my_templatetag.py inside app_name/templatetags, make sure you restart the Django development server (or ensure it restarted itself) every time you modify template tags. If the server does not restart, Django won't register the tags.

查看更多
女痞
5楼-- · 2020-02-08 05:34

Where is 'my_templatetag.py' stored? It should be stored in a directory called 'templatetags' which is within the app.

Please see: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/ if that isn't the case.

查看更多
女痞
6楼-- · 2020-02-08 05:36

I am using Django 1.11, and I was having the same problem. Some of the answers here are right, but some things may be missing. Here is what I did:

Quoting a previous user:

Create a folder called "templatetags" at the same level as models.py and views.py in your application folder

Your application must be in the INSTALLED_APPS in settings.py

The templatetags folder must have init.py

But, before you re-start the Django server, add this to the file that contains the tags:

from django import template
register = template.Library()

Then you can re-start the server.

查看更多
登录 后发表回答