13👍
The main scenario is to make certain variables available in your template. For example, the auth
context processor makes (amongst others) the user
variable available for use in your template so that you don’t have to pass it yourself. Although it’s quite a big paragraph, the Django documentation does quite a good job at explaining it.
In a nutshell: by adding context_instance=RequestContext(request)
to your render
call, all processors defined in your settings.py
(under the TEMPLATE_CONTEXT_PROCESSORS
variable) are executed in order. Each of these processors return a dict
with variables that are made available in the template. Using the default set, this means you do not have to add e.g. the user
, csrf
or messages
variables yourself: this is done by the processors.
An example for own context processor would be to add your main menu parameters to the template. Say you want to highlight the menu for the current category the user is viewing: by creating your own context processor that determines the current location, it could add some variables in the template that are used by your menu to do the highlighting.
9👍
Context instance is now deprecated in Django 1.8, and dictionary has been renamed to context.
Changed in Django 1.8:
The context argument used to be called dictionary. That name is deprecated in Django 1.8 and will be removed in Django 2.0.Deprecated since version 1.8:
The context_instance argument is deprecated. Simply use context.
So if you’re using a more recent version of Django, your call to the Render function should be:
from django.shortcuts import render
def my_view(request):
# View code here...
return render(request, 'myapp/index.html', {"foo": "bar"},
content_type="application/xhtml+xml")
Where {"foo": "bar"}
is your context. The missing context_instance
is (I presume) created by default now and populated with the required context of your request.
- Python/Django "BadStatusLine" error
- Django admin inline: select_related
- How to perform DB bitwise queries in Django?
3👍
I can think of two things:
-
Backwards compatibility. You can safely change all references from
render_to_response
torender
. -
You don’t want the context processors to be run for that particular view, you can pass in
None
in thecontext_instance
(saves a bit of overhead.)