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

来源:互联网 发布:山东大学网络教育首页 编辑:程序博客网 时间:2024/04/28 12:51

转载自: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 !

0 0
原创粉丝点击