Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: Why is RequestContext set as context_instance?

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)
like image 214
Paul Tarjan Avatar asked Dec 14 '22 03:12

Paul Tarjan


1 Answers

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
like image 59
André Eriksson Avatar answered Jan 28 '23 21:01

André Eriksson