gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:38:30 25 4
gpt4 key购买 nike

目前,因为我想访问我所有模板中的用户信息,所以我总是在我的所有 View 中使用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 )

这个和这个有什么不同?

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

return render_to_response( 'doors/orders/detail.html', context, context_instance = RequestContext( request ) )

如果在程序方面确实没有区别,那么最佳实践或首选方法是什么?

最佳答案

基本上没有区别。

在第二个示例中,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)

我的首选方法是使用 1.3+ 中的 render 快捷方式而不是 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))

关于django - 在 Django 中添加字典作为 RequestContext 的一部分或 render_to_response 的一部分有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9828465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com