Irrational Exuberance!

Writing Custom Contexts for Django

July 1, 2007. Filed under djangopython

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 file. Lets say that the file containing your context is at myproject/blog/, then we'll just add this snippet to our file:


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