Can custom Django filters access request.user?
Asked Answered
A

2

8

Is it possible to access the current User (i.e. user in the template context) from a custom template filter?

Obviously I can pass the user in as an argument, but if it's possible to just grab the current user, that would be more convenient.

Anonymous answered 13/7, 2011 at 18:5 Comment(0)
K
5

Django filters aren't given any special access to the context from which they are called, they're just plain old functions.

You'll need to pass in anything you want to use within the function.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

Kamal answered 13/7, 2011 at 18:11 Comment(2)
Sad. I suppose I could always do something with middleware or template context processors to set a thread local, but... yuck.Anonymous
Though first it feels PITA, replacing a filter with a template tag is quite easy with @register.simple_tag(takes_context=True)Ladino
C
0

See my answer here:

https://mcmap.net/q/603986/-django-accessing-the-requestcontext-from-within-a-custom-filter

But, in short, you CAN access the context from within a custom filter by extracting it from the call stack when, and only when, the filter is called during render.

This is, admittedly, a haphazard solution. Caveat emptor.

Catholicize answered 22/1, 2015 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.