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:
@@ python 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.
Great, now how do you convince every view to use a context without going and editing every single view? Like if I want some custom variable to be available in the nav bar, suddenly I have to edit all the views to use a context that has that nav bar (Do It Right Everywhere or DIRE), unless they were all using RequestContext already which of course reads from settings (aka uses globals). Sounds like a case of between a rock and a hard place or am I missing something? Thanks
AP
Reply to this entry