Search code examples
pythondjangodjango-templatesdjango-template-filters

Register custom filter in django


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


Solution

  • 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