在Django中添加字典作为RequestContext的一部分或render_to_response的一部分有什么区别?

hob*_*es3 2 django django-views

目前,因为我想访问user所有模板中的信息,所以我总是context_instance = RequestContext( request )在我的所有视图中使用.我也喜欢RequestContext因为它会自动处理csrf.

现在我通常只是将我的所有字典值放在里面RequestContext这样渲染

request_context = RequestContext( request, {
    'order'          : order,
    'order_comments' : order_comments,
    'comment_form'   : comment_form,
} )

return render_to_response( 'doors/orders/detail.html', context_instance = request_context )
Run Code Online (Sandbox Code Playgroud)

这有什么不同呢?

context = {
    'order'          : order,
    'order_comments' : order_comments,
    'comment_form'   : comment_form,
}

return render_to_response( 'doors/orders/detail.html', context, context_instance = RequestContext( request ) )
Run Code Online (Sandbox Code Playgroud)

如果程序方面没有真正的差异,那么这是最佳实践还是首选方法?

Yuj*_*ita 6

主要是没有区别的.

在第二个示例中,context参数更新了context_instance,但是它本身是空白的,因此这些示例之间最终没有区别.

这是源头......

if not context_instance:
    return t.render(Context(dictionary))
# Add the dictionary to the context stack, ensuring it gets removed again
# to keep the context_instance in the same state it started in.
context_instance.update(dictionary)
Run Code Online (Sandbox Code Playgroud)

对我来说,首选的方法是使用render1.3+ 的快捷方式而不是render_to_response快捷方式,因为对于我的大多数模板渲染,我都使用RequestContext.

from django.shortcuts import render_to_response, render

render(request, 'mytemplate.html', {'foo': 'bar'}) # automatically uses RequestContext
# vs 
render_to_response('mytemplate.html', {'foo': 'bar'}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)