user8171079
user8171079

Reputation: 346

Access logged in user from extra template tags file

I try to create a django template tag in which I need the logged in user, e.g. @register.filter() def foo(id): return Bar.objects.get(creator = request.user.id)

but I get a NameError, saying that request is not defined. Is there a way to access the request object in app_extras file?

Upvotes: 0

Views: 106

Answers (1)

wm3ndez
wm3ndez

Reputation: 723

You can use a simple_tag instead of a filter, which accepts a "takes_context" parameter.

@register.simple_tag(takes_context=True)
def foo(context):
    user = context['request'].user
    return Bar.objects.get(creator=user)

Keep in mind that "context" must be the first parameter.

Upvotes: 2

Related Questions