Getting RequestContext in Your Templates
May 10, 2008 | code, django | 10 comments
Lately, we’ve been taking over projects from people who began building their first site in Django, but either got in over their head or just found they didn’t have the time to continue. As I review the existing code, the first issue I typically see is using the render_to_response shortcut without including the RequestContext, preventing context processors from being used in the templates. The standard symptom is when people can’t access MEDIA_URL in their templates.
Here are a few ways to add RequestContext to your templates.
Option #1: Adding RequestContext to render_to_response
The Django documentation recommends passing RequestContext as an argument to render_to_response like this:
from django.shortcuts import render_to_response from django.template import RequestContext def my_view(request): # View code here... return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request))
This works, but as you can see, it adds a fair amount of repetitive code to your views ...