django context processors February 24, 2008

Django context processing is a lightweight method to expose variables in your views to your all of your templates.

As an example, let's say you wanted to use the user variable in all of your templates. You could manually pass request.user to all of your templates like this:

from django.shortcuts import render_to_response
from models import Post
import datetime

def index(request):
    now = datetime.datetime.now()
    return render_to_response('index.html', {'now': now, 'user': request.user})

def edit_post(request, id):
    post = Post.objects.get(id=id)
    return render_to_response('edit.html', {'post': post, 'user': request.user})

A more DRY way would be to use a context processor. Just define a function that returns a dictionary and include that function name in the settings.TEMPLATE_CONTEXT_PROCESSORS variable.

def add_user(request):
    return {'user': request.user}

# inside settings.py
TEMPLATE_CONTEXT_PROCESSORS = ('path.to.add_user',)

Now when you use render_to_response, be sure to pass in a RequestContext instance. The RequestContext instance will look for your template context processors and execute them, adding variables to your context:

# other imports go here
from django.template import RequestContext

# re-write of index to use context processor
def index(request):
    now = datetime.datetime.now()
    return render_to_response('index.html', {'now': now}, context_instance=RequestContext(request))

If you're not using render_to_response, just use the RequestContext class instead of a regular Context class. Be sure to pass in the request object as the first parameter and your normal dictionary as the second parameter:

c = Context({'now': datetime.datetime.now(), 'user': request.user})  # using a regular Context
c = RequestContext(request, {'now': datetime.datetime.now()})        # using a RequestContext

Imagine if you had to pass more than a user variable to your templates. What if you had to pass in 4 or 5 more variables? That's when context processing becomes a handy tool.

← see recent posts | comments closed 0 comment(s)

(c) Copyright 2007-2008 Hugh Bien. All Rights Reserved.

Contact Me | RSS Feed