Browsing other peoples’ code is a great way to learn new things about a language or framework. I never made it to the Django docs about Contexts, but the Pinax developers apparently did and I got a chance to learn this from them. This is a few sections of their code and how they use RequestContext in their apps.

If you are looking at the source of some of their views you might see how they are using it. Here is what it looks like in friends_app.friends

    return render_to_response(template_name, {
        "join_request_form": join_request_form,
        "invites_received": invites_received,
        "invites_sent": invites_sent,
        "joins_sent": joins_sent,
    }, context_instance=RequestContext(request))

So what extactly does context_instance=RequestContext(request) do? I took a look at the django documentation to find out more. And that led me to check the settings file and I found that there were quite a few things listed in TEMPLATE_CONTEXT_PROCESSORS.


I opened up friends_app.context_processors to see a bit more and it looked like this

from friends.models import FriendshipInvitation
def invitations(request):
    if request.user.is_authenticated():
        return {
            to_user=request.user, status="2").count(),
        return {}

This means that every view that has context_instance=RequestContext(request) in it will call the above function since it is listed in and it will provide the template variable, {{ invitations_count }}.

Using RequestContext makes it easy to have the common template variables available on every page and I will have to start using it more in my apps. So make sure you have from django.shortcuts import render_to_response and from django.template import RequestContext in your file and add your context processor to the settings file and you should be ready to add template vars to your contexts.

I use webfaction to host a lot of my django projects. It has an easy setup that will get you developing quickly and a great community of talented programmers. There is also a quick setup for rails, wordpress, and a lot more.

Related posts:

  1. How to Write Django Template Tags  Template tags can be useful for making your applications more reusable by other projects. For this example I will be...
  2. How to Write Reusable Apps for Pinax and Django   Pinax is a collection of reusable django apps that brings together features that are common to many websites. It...
  3. Quick Thumbnails in Django  I normally like to write code myself instead of installing some large script just to do one task for me....