I'm trying to understand the concept of context and context processor.
- What is a context and why do you use it?
- Is a context a value you need to have available in order to use in a template?
- Is a context and a context processor the same?
I'm trying to understand the concept of context and context processor.
The Context
is described quite well in the official documentation. In short:
In day-to-day use, mostly indirectly, because helper functions construct the Context
for you
See 1.: you only need it if you use the low-level api
No, a context processor is a function that takes a request and returns a dictionary of variables that are then available in all templates that are rendered with a RequestContext
, for example:
def get_stuff_from_session(request):
return {'stuff': request.session['stuff']}
When you use a Django Template, it is compiled once (and only once) and stored for future use, as an optimization. A template can have variable names in double curly braces, such as
{{ myvar1 }}
and{{ myvar2 }}
.A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like:
{myvar1: 101, myvar2: 102}
, when you pass this context to the template render method,{{ myvar1 }}
would be replaced with101
and{{ myvar2 }}
with102
in your template. This is a simplistic example, but really a Context object is the context in which the template is being rendered.As for a ContextProcessor, that is a slightly advanced concept. You can have in your
settings.py
file listed a few Context Processors which take in anHttpRequest
object and return a dictionary (similar to the Context object above). The dictionary (context) returned by the Context Processor is merged into the context passed in by you (the user) by Django.A use case for a Context Processor is when you always want to insert certain variables inside your template (for example the location of the user could be a candidate). Instead of writing code to insert it in each view, you could simply write a context processor for it and add it to the
TEMPLATE_CONTEXT_PROCESSORS
settings insettings.py
.Hope this makes sense. Thanks for taking the class!