user469652
user469652

Reputation: 51261

Django 1.4: How can I access request object in inclusion_tag

Code

@register.inclusion_tag('template.html', takes_context=True)
def include_client_side_bar(context):
    return {
        'STATIC_URL': settings.STATIC_URL,
        }

My code is will be something like this, I want to access request.user object inside this function, but I can't get it.

In the debugger, I can see these variables. enter image description here

As far as I can recall, I have made this successfully in django 1.3, did I miss something?

Upvotes: 1

Views: 971

Answers (2)

eos87
eos87

Reputation: 9353

try with request = context.get('request', None) if request key doesn't exists assign None value.

http://docs.python.org/library/stdtypes.html#dict.get

Update:

Also you can pass user to inclusion_tag, with something like this

# In your template_tag
@register.inclusion_tag('template.html', takes_context=True)
def include_client_side_bar(context, user):
    if user:
         pass # do something
    return {
        'STATIC_URL': settings.STATIC_URL,
    }

# in your template
{% include_client_side_bar user=request.user %}

Upvotes: 1

Alasdair
Alasdair

Reputation: 308909

Make sure you've included the request context processor in your TEMPLATE_CONTEXT_PROCESSORS setting, and that your view is rendered with a RequestContext.

Upvotes: 1

Related Questions