0

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?

Adrian
  • 71
  • 5
  • Check this [https://stackoverflow.com/questions/420703/how-do-i-add-multiple-arguments-to-my-custom-template-filter-in-a-django-templat](https://stackoverflow.com/questions/420703/how-do-i-add-multiple-arguments-to-my-custom-template-filter-in-a-django-templat) – Akash senta Jan 06 '22 at 04:46
  • Does this answer your question? [How do I add multiple arguments to my custom template filter in a django template?](https://stackoverflow.com/questions/420703/how-do-i-add-multiple-arguments-to-my-custom-template-filter-in-a-django-templat) – Akash senta Jan 06 '22 at 04:47
  • Also this can help [link](https://stackoverflow.com/a/47887651/1079086) – Akash senta Jan 06 '22 at 04:49

1 Answers1

2

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

Sy Ker
  • 2,047
  • 1
  • 4
  • 20