Accessing Session from Django Custom Tag

May 13, 2010

I have a website where there are many projects. If you switch between projects, then that change is stored in session and used to render some parts of the top level template, showing links to that project.

In order to do this, I needed to access the Django session from a custom tag.

from django import template
from django.conf import settings

class CurrentProjectNode(template.Node):
    """
    Return the passed in project name, or the one defined in the session
    """
    def __init__(self, pHtml):
        self.html = pHtml
    def render(self, context):
        try:
            lReturn = context['request'].session['CurrentProject']
        except KeyError:
            lReturn = self.html
        return lReturn

def current_project(parser, token):
    """
    Return the currently selected project name
    """
    return CurrentProjectNode("Default Project")

register = template.Library()
register.tag('current_project', current_project)

Once this tag is in use on template.html using {%current_project%}, all that remains to be done is to switch between projects when the template variables contain Project.

As I use a bespoke function render_auth for wrappering the render_to_response call, this was simply added there:

def render_auth(request, pTemplate, pParams=None):
    try:
        if pParams:
            request.session['CurrentProject'] = pParams['Project'].name
    except KeyError:
        pass

    return render_to_response(pTemplate, 
                          pParams, 
                          context_instance=RequestContext(request))