Django registration of tag library not working

Viewed 9651

I try to register my custom template tag library in django, but unfortunately it isnt working!

I want to create a custom include-tag and followed the instruction at: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags

I have created an app called 'tag_lib' (installed in settings.py) to put my template tags in. In the app folder is a dictionary called 'templatetags' containing an empty __init__.py and my my_tags.py.

my_tags.py contains:

from django import template


register = template.Library()


@register.inclusion_tag(filename='navbar.html', takes_context=True)
def navbar_context(context):
    return {
        'some_var': context['some_var'],
    }

When I restart my devserver and try to load the library with

{% load my_tags %} `

in a template, I'm getting the error:`

TemplateSyntaxError at /

'my_tags' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
static
staticfiles
tz

Any idea where I made a mistake?

Thanks.

4 Answers

I faced this problem to.what i did was just stop the server run and just run it again.It seems that django does not initialize tags (or resources in general) while running the server.hope it helps.

Just for a reminder, when using django under Windows, it is necessary to restart the development server (python.exe manage.py runserver) in at least two situations, which are:

  • when a new templatetag was created in an app
  • when static files were modified in the 'app/static/app/' folder

Hope this helps

I faced the same problem, but reloading the server doesn't work. So I solved it by this:

at project/setting.py I wrote the next, at TEMPLATE I registered libraries:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates'), ],
    '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',
        ],
        'libraries': {
            'my_tags': 'app.templatetags.blog_tags',
        }
    },
},

]

And the server restarted by itself.

Related