how to pass context to filter in django

193 Views Asked by At

I want to access context in filter:

NOT working example (showing what I want to get)

{% for phone in person.communicator_set.all|phones %}
{{ phone.number }}
{% endfor %}

templatetags/filters.py

@register.filter(takes_context=True)
def context_filter(context,queryset):
    return queryset.filter(validity_range__contains=context['context_date'])

But this doesn't work...

1

There are 1 best solutions below

4
Mohammad Golam Dostogir On

Updated code as per comments discussion.

Update your filter function with the code given below:

from django import template

register = template.Library()

@register.filter(takes_context=True)
def phones(context, queryset, *args, **kwargs):
    context_date = context.get('context_date', None)
    if context_date is not None:
        return queryset.filter(validity_range__contains=context_date)
    return queryset

After this in your template file you can call the custom filter as below:

  {% load filters %}

{% with context_date=your_date %}
    {% for phone in person.communicator_set.all|phones:**context %}
        {{ phone.number }}
    {% endfor %}
{% endwith %}