Search code examples
pythondjangodjango-templatesweb-development-serverdjango-custom-tags

TemplateSyntaxError 'apptags' is not a registered tag library


I have made a custom template tag , in apptags.py file which is inside templatetag folder and templatetag folder is inside my application folder, with the following code

from django import template
import datetime
register=template.Library()
@register.simple_tag(name="get_date")
def get_date():
    now = datetime.datetime.now()
    return now

and im using it in my html file as

% load static %}
{% load apptags %}
{% get_date as today %}
<h2>Today is {{today}} </h2>

and it is showing the below error:

TemplateSyntaxError at /exam/show-test/ 'apptags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz

P.S :- Templatetag is a package as i've made a init.py file inside it


Solution

  • You need to add your templatetags in your project settings.py file for Django to identify it.

    Add this to entry to your OPTIONS of TEMPLATES in settings.py file:

    'libraries':  {
                    '<template_tag name>': '<App_name>.templatetags.<template_tag name>',
                }
    

    Example:

    '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':  {
                    'dict_key': 'blogs.templatetags.dict_key',
                }