Getting RequestContext in Your Templates
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.
Option #2: Wrapper for render_to_response
Don’t repeat yourself. Create a wrapper like this, courtesy of Django Snippet #3
from django.shortcuts import render_to_response from django.template import RequestContext def render_response(req, *args, **kwargs): kwargs['context_instance'] = RequestContext(req) return render_to_response(*args, **kwargs)
Option #3: Use Generic Views
Django’s generic views include RequestContext by default. Although the docs show them being used in urls.py, you can just as easily use them in your views. James Bennet gave some examples of this technique on his blog back in ‘06. It looks something like this:
from django.views.generic import list_detail def my_view(request): # View code here... return list_detail.object_list_(request, queryset=Foo.objects.all(), extra_context=some_dict)
Most views can be distilled down to either a single object or list of objects with some extra variables thrown in. When they can’t, simply use direct_to_template.
Option #4: Getting Creative with Decorators
I came across a technique I hadn’t seen before a couple of days ago when poking around django-cashflow. It monkey patches render_to_response using option #1 above, then creates uses a decorator for it. The code looks like this:
def render_to(template_name): def renderer(func): def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output return render_to_response(request, template_name, output) return wrapper return renderer @render_to('my_template.html') def my_view(request): # View code here... return some_dict
Pretty slick.
How About You?
I use generic views for a few of reasons.
- It is less verbose than option #1
- Options 2 & 4 are clever, but I prefer to use built-ins whenever possible. One of the reasons I chose Python over Ruby is because it isn’t a TIMTOWTDI language. Wrappers and shortcuts are great, but they can also make it more difficult for someone else to jump into your code and start working. With generic views, you get sane defaults and everything is already fully documented and clear to other Django developers.
- They provide a standardized naming scheme for your templates. Again allowing other developers to jump right into your code without having to learn your style.
So how about you? What technique do you use and why?
Reader Comments
Got something to say?
This was written on May, 10 2008 and is filed in code, django.
Thanks for checking in on our blog today. Want to learn more about Lincoln Loop? Visit our home page.Categories
- portfolio
- code
- software
- company news
- trailmapping
- SEO
- wordpress
- presentation
- accessiblity
- subversion
- django
Archives
Elsewhere
What I’ve been up to online
-
#5247: patch6702.diff - Django Code - Trac
08.08.04, 20:30 # -
#5247: patch.diff - Django Code - Trac
08.08.04, 20:30 # -
Anybody want to split a hotel room for #DjangoCon?
08.07.31, 9:42 # -
Just got confirmation I'm on the invite list for #DjangoCon. Being a member does have its benefits. Couch surf or hotel?
08.07.31, 9:02 # -
Admin Image Widget
08.07.31, 6:28 # -
Follow @trailmapping for Trailmapping.com updates. Just pushed some slick jQuery into production tonight.
08.07.31, 1:53 # -
Munin :: com :: djangoproject.com :: trac_tickets
Graphs of trac tickets for Django
08.07.29, 12:00 # -
Automating tests in Django | Eric's Site
Generate tests by simply clicking through your development site.
08.07.24, 9:23 # -
Creator/updater fields for admin
08.07.21, 16:16 # -
fairview computing :: Django geography hacks
Nice base for a reusable Locations app for Django
08.07.10, 16:58 # -
working with a designer
Great tips on how to be a good client to your designer and get the most out of him at the same time.
08.07.09, 23:45 # -
Fluency Admin at deanjrobinson.com
Elegant WordPress admin interface
08.07.09, 16:43 # -
Search Docs with Shortwave
08.07.08, 5:00 # -
django-chunks - Google Code
Handy little project for managing CMS content snippets.
08.07.07, 16:53 # -
Norbauer Inc: The Boston Ruby on Rails Development Consulting Firm
I love 1 page websites. Short, sweet and to-the-point.
08.07.02, 9:21 #
What about django.views.generic.simple.direct_to_template?
I’ve always used
render_to_response(‘template’, RequestContext(request, data_dict))
which seems to work fine, and isn’t so bad.
Like David suggested, just use the direct_to_template view as you would the render_to_response template (but passing request as the first argument).
Easy peasy.
David, I mentioned direct_to_template in Option 3 (my personal choice), but only use it when one of the other generic views doesn’t make more sense.
+1 for direct_to_template! simple + beautiful and without inventing the wheel.
I do this. I do repeat the “context = RequestContext(request)” line in (most)every view but I like being explicit like that.
context = RequestContext(request)
context[“somevar”] = “foo”
context[“othervar”] = “bar”
return render_to_response(“template.html”, context)
Nice writeup. Another good resource to point people to.
thanks for your code!
it helps me a lot in using RequestContext
In fact, direct_to_template is more a replacement for #1 given the fact it does exactly the same as #2, otherwise, if a generic_view already exists (#3), it’s more interesting to use it like you mention.
David, direct_to_template is a generic view.
django.views.generic.simple.direct_to_template :)