Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.10.1 'my_templatetag' is not a registered tag library. Must be one of:

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?

like image 892
Sliljedal Avatar asked Nov 18 '16 21:11

Sliljedal


2 Answers

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.

like image 112
lmiguelvargasf Avatar answered Nov 18 '22 20:11

lmiguelvargasf


From Django 1.9, you can load those new tags/filters in settings like this:

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',
            
            }
    },
},

]

If you have templatetag dir in your project dir (not in an app dir), then above method is recommended.

Example-
enter image description here

Quoting: https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#:~:text=It%20also%20enables%20you%20to%20register%20tags%20without%20installing%20an%20application.

like image 106
Dat TT Avatar answered Nov 18 '22 20:11

Dat TT