class RequestContext(request, dict_=None, processors=None)
[source]
Django comes with a special Context
class, django.template.RequestContext
, that acts slightly differently from the normal django.template.Context
. The first difference is that it takes an HttpRequest
as its first argument. For example:
c = RequestContext(request, { 'foo': 'bar', })
The second difference is that it automatically populates the context with a few variables, according to the engine’s context_processors
configuration option.
The context_processors
option is a list of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context. In the default generated settings file, the default template engine contains the following context processors:
[ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ]
In addition to these, RequestContext
always enables 'django.template.context_processors.csrf'
. This is a security related context processor required by the admin and other contrib apps, and, in case of accidental misconfiguration, it is deliberately hardcoded in and cannot be turned off in the context_processors
option.
Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained below.
When context processors are applied
Context processors are applied on top of context data. This means that a context processor may overwrite variables you’ve supplied to your Context
or RequestContext
, so take care to avoid variable names that overlap with those supplied by your context processors.
If you want context data to take priority over context processors, use the following pattern:
from django.template import RequestContext request_context = RequestContext(request) request_context.push({"my_name": "Adrian"})
Django does this to allow context data to override context processors in APIs such as render()
and TemplateResponse
.
Also, you can give RequestContext
a list of additional processors, using the optional, third positional argument, processors
. In this example, the RequestContext
instance gets a ip_address
variable:
from django.http import HttpResponse from django.template import RequestContext, Template def ip_address_processor(request): return {'ip_address': request.META['REMOTE_ADDR']} def client_ip_view(request): template = Template('{{ title }}: {{ ip_address }}') context = RequestContext(request, { 'title': 'Your IP Address', }, [ip_address_processor]) return HttpResponse(template.render(context))
Please login to continue.