Access request in django custom template tags


My code in

from django import template

register = template.Library()

def address():
    address = request.session['address']
    return {'address':address}

in '':


but I got an error:

TemplateSyntaxError at /items/

Caught an exception while rendering: global name 'request' is not defined

Original Traceback (most recent call last):
  File "C:\Python25\lib\site-packages\django\template\", line 71, in render_node
    result = node.render(context)
  File "C:\Python25\lib\site-packages\django\template\", line 915, in render
    dict = func(*args)
  File "C:\p4\projects\myproject\..\myproject\invoice\templatetags\", line 9, in address
    address = request.session['address']
NameError: global name 'request' is not defined

I referenced this one In Django, is it possible to access the current user session from within a custom tag?.

5/23/2017 11:46:54 AM

Accepted Answer

request is not a variable in that scope. You will have to get it from the context first. Pass takes_context to the decorator and add context to the tag arguments.

Like this:

@register.inclusion_tag('new/userinfo.html', takes_context=True)
def address(context):
    request = context['request']
    address = request.session['address']
    return {'address':address}
11/25/2014 10:19:09 PM

I've tried solution from above (from Ignacio Vazquez-Abrams) and it actually didn't work until I've found out that context processors works only with RequestContext wrapper class.

So in main view method you should add the following line:

from django.template import RequestContext        
return render_to_response('index.html', {'form': form, }, 
                              context_instance = RequestContext(request))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow