How to get at request in a template

I needed to get at the request in a template which had been called ‘direct_to_template’. To make the request available, you need to modify the TEMPLATE_CONTEXT_PROCESSORS variable.

Add this to your settings file


TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

Then you can use {{ request }}

5 Responses to “How to get at request in a template”

  1. Erik says:

    Django noob here: is this any better or worse then simply passing along request from the view?

  2. Peter says:

    If you really need to access request across multiple views, it’s smarter to use the context processor.

  3. Enrico says:

    I think you forgot, you need to use RequestContext in your view in order to get the request available in the template.

    That’s because the request isn’t globally available.

    Check this page:
    http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/

  4. Rachel says:

    This is referring to the case where you’re just calling a template directly from the urls.py with ‘direct_to_template’ so no opportunity to do anything in the view.

    I hadn’t made that clear, thanks, I’ve added a wee note on that.

  5. Marc Remolt says:

    All generic views automatically use RequestContext, so with direct_to_template you can use {{ request }}.

    For render_to_response, you have to manually pass it to activate the context processors:

    return render_to_response(‘template.html’, { my_context_as_dict }, context_instance = RequestContext(request))

Leave a Reply