When is it appropriate to use Django context processors?
-
06-07-2019 - |
Question
If about half of my views require the same data set, is it appropriate to use a context processor to make the data always available, or is there a better way to avoid repeating the code to get that data across several views without querying the data if it won't be used in the view?
Solution
The RequestContext
initializer will run any context processors listed in the settings file, but it also takes a list of additional processors to run. Any general purpose context processors can be put in settings.py and more specific ones can be added to the RequestContext
on a case-by-case basis.
Leave RequestContext
out altogether to not run any context processors.
# want context processors listed in settings.py as well as some more specific ones
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request, processors = extra_processors))
# want only context processors listed in settings.py
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request))
# no context processors
return render_to_response('template.html', {'foo':'bar'})
OTHER TIPS
You can filter out which views actually use context processors by only passing RequestContext(request)
only to those which need it, e.g.:
# want context processors
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request))
# no context processors
return render_to_response('template.html', {'foo':'bar'})