Writing Custom Contexts for Django

July 1, 2007. Filed under django 72 python 56

In building this site I ran into a number of situations where I was using generic views, but I needed another piece of information that simply wasn't accessible. Sure, I could write a bunch of custom views, but thats how I handled my first large Django project, and I didn't have any intention of doing that again (so much time wasted through irrational fearing of generic views, bah).

Fortunately there is a really fantastically easy way to solve this problem: writing your own contexts.

What is a context?

A context is just some information. They will usually be QuerySets, but they could be anything. They will be available from within your templates. Oh, and they are a breeze to make.

When building my site I wanted to have a selection of random entries available on the navigation bar on each page, lets look at how we can do this with a context.

Contexts are simply functions that take one argument, request, and return a dictionary of values. The one I wrote looks like this:

from blog.models import Entry

def blog(request):
    random = Entry.current.all().order_by('?')[:3]
    return { 'random_entries' : random, }

And... thats it. Now you'll need to make a quick entry in your settings.py file. Lets say that the file containing your context is at myproject/blog/context.py, then we'll just add this snippet to our settings.py file:

TEMPLATE_CONTEXT_PROCESSORS = (
      "django.core.context_processors.auth",
      "django.core.context_processors.debug
      "django.core.context_processors.i18n",
      "django.core.context_processors.media",
      "myproject.blog.context.blog",
      )

Its that easy, and yet not particularly well documented. Ah well, go now and conquer.