考虑一下:
return render(request, 'index.html', {..context..})
return render_to_response('index.html', {..context..})
一方面,render
更干净,更Pythonic。另一方面,您使用request
作为你的第一个论点,我发现它是多余且令人困惑的。所以我开始想知道更大的差异......
根据the docs https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#django.shortcuts.render:
render() 与调用 render_to_response() 相同
context_instance 参数强制使用 RequestContext。
所以区别仅在于使用RequestContext。那么RequestContext 重要的是什么?让我们看看再次文档 https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext:
一个特殊的 Context 类 [...] 的行为与
正常的 django.template.Context。第一个区别是它需要
HttpRequest 作为其第一个参数。
好的。这根本不重要
第二个区别是它自动填充上下文
根据您的 TEMPLATE_CONTEXT_PROCESSORS 有一些变量
设置 [...] 除了这些之外,RequestContext 总是使用
django.core.context_processors.csrf [...]它是故意硬编码的
且不能被 TEMPLATE_CONTEXT_PROCESSORS 关闭
环境。
所以这是重要的部分 - 确保所有上下文处理器正常工作,重点是 csrf。真的,回到我的第一个例子,these实际上是一样的:
return render(request, 'index.html', {...})
return render_to_response('index.html', {...}, context_instance=RequestContext(request))
现在,第二个例子显然要糟糕得多,整个事情似乎过于复杂。所以我的大问题是Why use render_to_response
根本吗?为什么不弃用它呢?
我想到的其他问题:
- 难道就没有更好的办法来强制执行吗
RequestContext
作为默认值?
- 有没有办法避免通过
request
作为一个论点?这是非常多余的。我发现一篇博文 http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/展示如何将 render_to_response 变成一个易于使用的装饰器。我们不能做类似的事情吗render
?
- 对于这个问题有什么想法吗(如果这是一个问题的话)?我在其中什么也没看到未来弃用时间表 https://docs.djangoproject.com/en/dev/internals/deprecation/。我觉得这特别令人困惑,考虑到
render
与 django 1.3 一起出现具体来说解决 render_to_response 的问题 https://stackoverflow.com/a/5693814/2387772, 然后每个人都同意 https://stackoverflow.com/questions/5154358/django-what-is-the-difference-between-render-render-to-response-and-direc 你不应该使用 http://rayed.com/wordpress/?p=1445 render_to_response
我知道这似乎有点偏离主题,但我希望得到能解释原因的答案render_to_response
留在周围和\或使用用例的示例render_to_response
将优先于render
(如果有的话)