在视图中,render()
、render_to_response()
和direct_to_template()
之间有什么区别(在python/djangoob可以理解的语言中)?
例如从Nathan Borror's basic apps examples
def comment_edit(request, object_id, template_name='comments/edit.html'):
comment = get_object_or_404(Comment, pk=object_id, user=request.user)
# ...
return render(request, template_name, {
'form': form,
'comment': comment,
})
但我也看到了
return render_to_response(template_name, my_data_dictionary,
context_instance=RequestContext(request))
以及
return direct_to_template(request, template_name, my_data_dictionary)
有什么区别,在任何特殊情况下使用什么?
渲染是
所以
render_to_response
之间实际上没有区别,只是它包装了您的上下文,使模板预处理器工作。直接到模板是一个generic view。
在这里使用它是没有意义的,因为视图函数的形式有超过
render_to_response
的开销。用尤里、法比奥和弗罗斯特的话来解释Django noob(即我)的答案——几乎可以肯定是一个简化,但却是一个好的起点?
render_to_response()
是“原始”的,但要求您几乎一直将context_instance=RequestContext(request)
放入PITA中。direct_to_template()
设计为仅在url.py中使用,而不在views.py中定义视图,但是它can be used in views.py to avoid having to type RequestContextrender()
是自动提供context_instance=Request
的render_to_response()
的快捷方式。。。。 它在django开发版本(1.2.1)中可用,但许多人已经创建了自己的快捷方式,比如this one、this one或者最初让我崩溃的那个,Nathans basic.tools.shortcuts.pyhttps://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render
render()
是1.3中render_to_response
的一个全新快捷方式,它将自动使用RequestContext
,从现在起我将非常肯定地使用它。https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response
render_to_response
是教程等中使用的标准呈现函数。要使用RequestContext
,必须指定context_instance=RequestContext(request)
https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template
direct_to_template
是我在视图中(而不是在我的url中)使用的通用视图,因为像新的render()
函数一样,它会自动使用RequestContext
及其所有的context_processor
但是应该避免使用
direct_to_template
,因为不赞成使用基于函数的泛型视图。使用render
或实际的类,请参见https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/我很高兴我很久没打字了。
相关问题 更多 >
编程相关推荐