0

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

2 Answers 2

3

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

according to django documentions:

The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the init.py file to ensure the directory is treated as a Python package

in your case, folder name is templatetag that is wrong
so you should rename it to templatetags .
otherwise you should follow @Ram answer as:

Alternatively, template tag modules can be registered through the 'libraries' argument to DjangoTemplates. This is useful if you want to use a different label from the template tag module name when loading template tags. It also enables you to register tags without installing an application

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.