2

. is my project root, where manage.py resides. I have a base template at ./templates/base.html. I have a custom template tag in ./app/templatetags/mytags.py

from django import template

register = template.Library()

@register.unread_tag
def get_unread(user):
    return user.notification_set.filter(viewed=False).count()

How do I make this tag usable for base.html, from which all app-level templates inherit.

yayu
  • 7,758
  • 17
  • 54
  • 86

2 Answers2

2

Your tag definition is not correct. You need to use register.simple_tag decorator:

@register.simple_tag(name='unread')
def get_unread(user):
    return user.notification_set.filter(viewed=False).count()

Then, you need to load the tag into the template:

{% load mytags %}

Then, you can use the tag in the template:

{% unread request.user %}
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I am using as {% unread request.user %} I get the error that it takes two arguments and only 1 is provided. On removing request.user and restarting dev server the error remains the same. – yayu Jun 18 '14 at 15:03
  • thanks. On a different note, I am getting `'str' object has no attribute 'notification_set'` which is being thrown on the line `return user.notification_set.filter(viewed=False).count()`. On the shell, when I try `u.notification_set.filter(viewed=False).count()` where u is a User instance, I get the right answer. Would you know why? – yayu Jun 18 '14 at 17:11
0

Quite an old question but things have changed since this was asked.
You can load a custom tag for ALL templates within the project in settings.py using the key builtins in OPTIONS of settings.TEMPLATES

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',
        ],
        'builtins': [
            'app.templatetags.mytags',
        ],
    },
}]

You can read more about the options in the Django doc - DjangoTemplates of built-in backends.

This option is supported from Django 1.9 onwards.

slajma
  • 1,609
  • 15
  • 17