views:

745

answers:

2

It seems most documentation recommends :

template_values = {}
template_values["foo"] = "bar"
return render_to_response(path, template_values, context_instance=RequestContext(request)

Why don't I use :

template_values = RequestContext(request)
template_values["foo"] = "bar"
return render_to_response(path, template_values)
+2  A: 

RequestContext doesn't inherit from dict, and as such is not guaranteed to implement all of dict's methods (and it doesn't), and any functions that operate on dicts may not work, either. Lastly, there's no reason to; it's better to consider it an opaque object whose implementation may change. Using a dict to provide the template's context has all the benefits and none of the drawbacks of RequestContext.

Update

To produce less boilerplate code, here are two utility functions I use. I put them in a shortcuts.py file at the base of my project.

from django.template import RequestContext
def render_template(request, template, data=None):
    "Wrapper around render_to_response that fills in context_instance for you."
    response = render_to_response(template, data,
                              context_instance=RequestContext(request))
    return response

def boilerplate_render(template):
    "Factory function for creating simple views that only forward to a template"
    def view(request, **kwargs):
        response = render_template(request, template, kwargs)
        return response
    return view

Usage:

def my_view(request):
    # Do stuff here...
    return render_template(request, 'my_template.html', {'var1': 'value', etc..})

my_view2 = boilerplate_render('my_template2.html') # Takes no context parameters
Cide
wonderful. thank you. my last line seems kind of verbose, and appears at the end of every one of my views. any recommendations so that I don't keep copying and pasting this?
Paul Tarjan
Yes! Create a shortcut. I'll edit my reply to present mine.
Cide
A: 

In regards to "boiler-plate code", this is already built in to Django. Just use the generic view:

from django.views.generic.simple import direct_to_template

def my_view(request):
    # Do stuff here...
    return direct_to_template(request, 'my_template.html', {'var1': 'value', etc..})
SmileyChris