Mon, 11 Jan 2010

Creating a custom context processor

Django does a great job with template inheritance using base.html and
{% extends variable %}, etc. The django docs give good clear examples. But the
docs are not too clear on how to inherit objects throughout a website. The
answer lies with creating a custom context processor and is really quite
simple.

At your project root level, create a new file context_processors.py. You can
actually have this file reside anywhere, just make sure you point to it
correctly in your TEMPLATE_CONTEXT_PROCESSORS, which I explain below. 

Drop in your code that retrieves/creates whatever object you want available
throughout your website.  Here is an example:

-----
def groupCalendar(request):
    """ Returns a one-month calendar """
    from local1042.groupcalendar.models import GroupCalendar
    mycalendar = GroupCalendar()
    group = 4
    count = 1
    onemonth_cal = mycalendar.buildcalendar (group, \
        mycalendar.current_year, mycalendar.current_month, count)
    return { 'onemonth_cal': onemonth_cal }
-----

As you can see, you return a dictionary. Make sure you chose a variable name
that won't be used elsewhere as it will be stepped on or will step on a
pre-existing variable by the same name.

Then in your settings.py file, activate your new processor by adding:

TEMPLATE_CONTEXT_PROCESSORS = (
    '.....'
    'local1042.context_processors.groupCalendar',
    '.....'
)

Note you should have other entries already, so just add your new entry.

Now, in your base.html file or other blocks, retrieve your object by simply
calling {{ onemonth_cal }}.

One more thing: If you use render_to_response in your views, then you need to
use a RequestContext instead of a Context instance. So in a view, your code
may look like this:

-----
return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))
-----


Posted at: 01:41 | category: /django | Comments ()