consider this:
return render(request, 'index.html', {..context..})
return render_to_response('index.html', {..context..})
On the one hand, render
is cleaner and more pythonic. On the other, you use the request
as your first argument which I find redundant and confusing. So I started wondering about the bigger differences...
According to the docs:
render() is the same as a call to render_to_response() with a context_instance argument that forces the use of a RequestContext.
So the difference is only in using RequestContext. So what's important about RequestContext? Let's look at the docs again:
a special Context class [...] acts slightly differently than the normal django.template.Context. The first difference is that it takes an HttpRequest as its first argument.
Ok. That hardly matters at all
The second difference is that it automatically populates the context with a few variables, according to your TEMPLATE_CONTEXT_PROCESSORS setting [...] In addition to these, RequestContext always uses django.core.context_processors.csrf [...] it is deliberately hardcoded in and cannot be turned off by the TEMPLATE_CONTEXT_PROCESSORS setting.
So this is the important part - making sure all context processors work properly, with an emphasis on csrf. So really, to go back to my first example, these are actually the same:
return render(request, 'index.html', {...})
return render_to_response('index.html', {...}, context_instance=RequestContext(request))
Now, The second example is obviously far worse, the whole thing seems woefully overcomplicated. So my big question is Why use render_to_response
at all? Why not deprecate it?
Other questions that come to mind:
- Isn't there a better way to enforce
RequestContext
as the default? - Is there a way to avoid passing
request
as an argument? It's terribly redundant. I found a blog post showing how to make render_to_response into an easy to use decorator. Can't we do something similar withrender
? - Is there any thought about this issue (if it is an issue at all)? I see nothing of it in the future deprecation timeline. I find it especially confusing, considering
render
came about with django 1.3 specifically to address the problems with render_to_response, and that everyone agrees you shouldn't userender_to_response
I know it seems a little off-topic, but I'm hoping to get answers that will explain why render_to_response
is staying around and\or examples of use-cases where using render_to_response
will be preferred over render
(if there are any)