Register custom filter in django

24,180

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
Share:
24,180
user2954587
Author by

user2954587

mediocre at best django, angular, rails

Updated on July 09, 2022

Comments

  • user2954587
    user2954587 almost 2 years

    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

  • user2954587
    user2954587 almost 10 years
    That's not my issue, you can use both methods as described in the docs
  • alecxe
    alecxe almost 10 years
    @user2954587 yup, but still, you didn't have register defined.
  • user2954587
    user2954587 almost 10 years
    Understood, but still not working. Any other ideas or ways to test what's going on?
  • user2954587
    user2954587 almost 10 years
    no errors. I'm finding it tough to debug as it seems it's failing 'silently' or it's just not even getting called
  • alecxe
    alecxe almost 10 years
    @user2954587 ok, what if you omit |floatformat:"0" and try it with only intcomma filter applied?
  • alecxe
    alecxe almost 10 years
    @user2954587 also, I suspect there could be another reason. There is a built-in intcomma filter from django.contrib.humanize. Try renaming your filter to smth different.
  • user2954587
    user2954587 almost 10 years
    tried that and no luck. I've been restarting the server too and that doesn't seem to be the issue.
  • user2954587
    user2954587 almost 10 years
    extremely stupid error on my part with collectstatic. Thank you for your patience!