<?xml version="1.0" encoding="iso-8859-1"?>
<!-- name="generator" content="pyblosxom/1.3.2 2/13/2006" -->
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN" "http://my.netscape.com/publish/formats/rss-0.91.dtd">

<rss version="0.91">
<channel>
<title>Rustybear Blog 11 Jan 2010</title>
<link>http://www.rustybear.com/cgi-bin/pyblosxom.cgi</link>
<description>Rustybear Blog</description>
<language>en</language>
<item>
  <title>Creating a custom context processor</title>
  <link>http://www.rustybear.com/cgi-bin/pyblosxom.cgi/django/context-processor.html</link>
  <description><![CDATA[
<pre>
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))
-----


</pre>

]]></description>
</item>

</channel>
</rss>
