Robert Townley Robert Townley - 4 months ago 22
Python Question

Purpose of a Django template context object?

In one of our applications (running Django 1.8) we tend to render templates by passing a dictionary into the context parameter of the render() function and returning them as part of a view. For example:

from django.views.generic import View

class HomePageView(View):

def get(self, request, *args, **kwargs):
context = {'foo': 'bar', 'foo2': 'bar2'}
return render(request, "page.html", context)


Now that I've started looking for it, I'm seeing examples of people using Django "context" objects rather than dictionaries.

from django.views.generic import View
from django.template import Context

class HomePageView(View):

def get(self, request, *args, **kwargs):
context = Context()
context['foo'] = 'bar'
context['foo2'] = 'bar2'
return render(request, "page.html", context)


The documentation shows that this Context object can be interacted with in ways similar to a dictionary (pop, copy, key assignment, etc) and has a flatten() method that lets you compare it to a dictionary.
https://docs.djangoproject.com/en/1.8/ref/templates/api/#playing-with-context.

My question is: Is there any reason why I would ever want to use a Context object rather than a dictionary? I can see how someone might find the subclass of RequestContext useful if they wanted easy access to request variables, but I think I'm missing the context object's utility.

Answer Source

A Python dictionary is a mapping between known keys and variable values. A Context() is similar to dictionary, but a Context() provides additional functionality.

So, when rendering a template, you need a context. This can be an instance of django.template.Context, but Django comes also with a subclass django.template.RequestContext that acts slightly differently.

The render() shortcut creates a RequestContext unless it's passed a different context instance explicitly.

[...]

RequestContext and context processors were created to solve the problem of redundancy. Context processors let you specify a number of variables that get set in each context automatically without having to specify the variables in each render() call.

[...]

  • Keep in mind that any context processor in TEMPLATE_CONTEXT_PROCESSORS (in settings) will be available in every template prowered by that setteings file.

  • Custom context perocessors can live anywhere in your code base. All Django care about is that your custom context processors are pointed to by the context_processors option in your TEMPLATES settings, or context_processors argument of Engine if you're using it directly. With that said, the is convention is to save them in a file called con_text_processors.p within your app or project.

Source: Mastering Django: Core. The complete Guide to Django 1.8LTS

More info: official documentation: RequestContext