Surprise in Django render()

The doc says render() (Note 1) is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.

It happens that render() takes a request object as its first argument, and a context_instance and a dictionary as two of its optional arguments. The context_instance is the context instance to render the template with. By default, the template will be rendered with a RequestContext instance (filled with values from request and dictionary).

As a Django beginner, I naively assume the request object will be automatically available in the template as I pass it as the first argument in the first place, and also because the context_instance argument forces the use of a RequestContext instance which is filled with values from the request object. Turns out that is not the case.

The request object is for the construction of the RequestContext only, which by default (as of Django 1.7) does not include the request object itself (Note2). It took me some time to figure that out.

To have the request object available in the template, I will have to pass it to render() in the dictionary argument:
    return render(request, template_name, {'request':request})
Or enable the request context processor at the settings, such that the request object will be automatically added to every RequestContext instance:
=== settings.py ===

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS

No comments: