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:
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
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:
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:
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?