Home > front end >  How to have two arguments in a django custom filter
How to have two arguments in a django custom filter

Time:01-06

I am trying to manipulate two objects for a calculation, however I am getting the error:"Invalid filter"

In the html frontend I have a nested loop with objects: units and person as following:

{{units|myFilter:person}}

where units has several objects and person only has one.

my filter is defined by:

def myFilter(units,person):
    n = 0
    for i in units:
        if i.name == person.name:
            n = n   1
    return n

But is it not working, any ideas or suggestions please?

CodePudding user response:

You can register a simple_tag function which accepts any number of positional or keyword arguments;

from django import template

register = template.Library()

@register.simple_tag
def my_tag(a, b):
    print(a, b)

    return 'What you need'

And this is how to use it in your template;

{% my_tag 123 "abcd" %}

Here is the documentation; https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#simple-tags

  •  Tags:  
  • Related