Context processors are awesome.
Say you have a different user model and you want to include
that in every response. Instead of doing this:
def myview(request, arg, arg2=None, template='my/template.html'):
''' My view... '''
response = dict()
myuser = MyUser.objects.get(user=request.user)
response['my_user'] = myuser
...
return render_to_response(template,
response,
context_instance=RequestContext(request))
Context processes give you the ability to pass any variable to your
templates. I typically put mine in 'my_project/apps/core/context.py
:
def my_context(request):
try:
return dict(my_user=MyUser.objects.get(user=request.user))
except ObjectNotFound:
return dict(my_user='')
In your settings.py
add the following line to your TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS = (
'my_project.apps.core.context.my_context',
...
)
Now every time a request is made it includes the my_user
key automatically.
I wrote a blog post about this a few months ago so I'm just going to cut and paste:
Out of the box Django gives you several signals that are
incredibly useful. You have the ability to do things pre and
post save, init, delete, or even when a request is being
processed. So lets get away from the concepts and
demonstrate how these are used. Say we’ve got a blog
from django.utils.translation import ugettext_lazy as _
class Post(models.Model):
title = models.CharField(_('title'), max_length=255)
body = models.TextField(_('body'))
created = models.DateTimeField(auto_now_add=True)
So somehow you want to notify one of the many blog-pinging
services we’ve made a new post, rebuild the most recent
posts cache, and tweet about it. Well with signals you have
the ability to do all of this without having to add any
methods to the Post class.
import twitter
from django.core.cache import cache
from django.db.models.signals import post_save
from django.conf import settings
def posted_blog(sender, created=None, instance=None, **kwargs):
''' Listens for a blog post to save and alerts some services. '''
if (created and instance is not None):
tweet = 'New blog post! %s' instance.title
t = twitter.PostUpdate(settings.TWITTER_USER,
settings.TWITTER_PASSWD,
tweet)
cache.set(instance.cache_key, instance, 60*5)
# send pingbacks
# ...
# whatever else
else:
cache.delete(instance.cache_key)
post_save.connect(posted_blog, sender=Post)
There we go, by defining that function and using the
post_init signal to connect the function to the Post model
and execute it after it has been saved.