Another way of writing custom contexts for Django
Posted on Fri 27 Jan 2012 under Web Development

While searching and experimenting for ways to pass context variables to templates in Django, I found a way that avoids the longer route of passing a custom context function through TEMPLATE_CONTEXT_PROCESSORS in the settings file and using RequestContext in every view function.

In this approach, you write a function in the views.py file (or anywhere) where a dictionary containing the context variables is returned. Something like shown below:

def custom_context():
    return {'SITE_TITLE': settings.SITE_TITLE,
            'archives': get_archives(),
            'categories': Category.objects.all()}

Then, we use this dictionary to update the context of a given view function:

from django.shortcuts import render_to_response

def view_page(request, slug):
    page = Page.objects.filter(slug=slug)[0]
    context = {'page': page}
    context.update(custom_context())
    return render_to_response('blog/view_page.html', context)

That's it folks! I hope it helps.


blog comments powered by Disqus