Register custom filter in django

user2954587 picture user2954587 · Aug 2, 2014 · Viewed 21.8k times · Source

My filter is not being registered and not sure where it's getting tripped up.

In test/templatetags

__init__.py
test_tags.py

test_tags.py includes

from django import template

register.filter('intcomma', intcomma)

def intcomma(value):
    return value + 1

test/templates includes pdf_test.html with the following contents

{% load test_tags %} 
<ul>
    <li>{{ value |intcomma |floatformat:"0"</li>
</ul>

float format works fine but no luck on intcomma

Answer

alecxe picture alecxe · Aug 2, 2014

First of all, you haven't defined register:

To be a valid tag library, the module must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered.

Also, I usually decorate the function with register.filter:

from django import template

register = template.Library()

@register.filter
def intcomma(value):
    return value + 1