前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【django】django render()和render_to_response()和direct_to_template()和locals()

【django】django render()和render_to_response()和direct_to_template()和locals()

作者头像
蛮三刀酱
发布2019-09-10 20:05:54
5710
发布2019-09-10 20:05:54
举报

转载自:https://www.douban.com/note/278152737/

前两者区别stackoverflow给了较明确的答案

参考网址:http://stackoverflow.com/questions/5154358/django-what-is-the-difference-between-render-render-to-response-and-direc

自django1.3开始:render()方法是render_to_response的一个崭新的快捷方式,前者会自动使用RequestContext。而后者必须coding出来,这是最明显的区别,当然前者更简洁。

return render_to_response('blog_add.html',{'blog': blog, 'form': form, 'id': id, 'tag': tag},

context_instance=RequestContext(request))

return render(request, 'blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})

stackoverflow里还给了return direct_to_template(request, template_name, my_data_dictionary)这样一个例子,关于其解释:

direct_to_template() is designed to be used just in urls.py without a view defined in views.py but it can be used in views.py to avoid having to type RequestContext.

direct_to_template is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py.

direct_to_template()还没用到过,不再赘述,留下此方法,备用

locals()用法:locals()可以直接将函数中所有的变量全部传给模板。当然这可能会传递一些多余的参数,有点浪费内存的嫌疑,对可读性有影响,不推荐。

return render(request, 'blog_add.html',locals())

那么长一段代码精简到三分之一的长度。有种爽歪歪的感觉!feel well !

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年12月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档