Django中的response

时间:2019-06-03 18:21:28   收藏:0   阅读:116

render_to_response

render_to_response('index.html', locals(),context_instance=RequestContext(request))

参数顺序:(template_name, dictionary=None, context_instance=None)

在django模板系统中,有两种封装模板变量的类,一个是django.template.Context,这是最常用的,我们在使用render_to_response方法的时候传入的第二个dictionary参数,就会被这个Context类封装一次,然后传到模板当中。

另一个是django.template.RequestContext,它和Context类相比有两个不同之处。

第一个不同的是,在生成一个RequestContext变量的时候,需要传入一个HttpRequest对象作为它的第一个参数。

其次,它会增加一些自动注入模板的变量,这些变量由settings中的TEMPLATE_CONTEXT_PROCESSORS中声明的方法返回,TEMPLATE_CONTEXT_PROCESSORS中的方法都接收一个HttpRequest对象,最终return一个dict。这个dictionary里面的元素就会成为RequestContext中自动注入模板的变量。比如django.contrib.auth.context_processors.auth就会返回user、messages、perms变量

# in django/contrib/auth/context_processors.py
def auth(request):
    """ ignore doc string """
    def get_user():
        ....
 
    return {
        'user': SimpleLazyObject(get_user),
        'messages': messages.get_messages(request),
        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
    }

有时候会用到dictionary=locals()这种操作,这是将当前域的所有局部变量都赋给dictionary

Response与HttpResponse的区别

原文:https://www.cnblogs.com/luozx207/p/10968572.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!