render_to_response('index.html', locals(),context_instance=RequestContext(request))
参数顺序:(template_name, dictionary=None, context_instance=None)html
在django模板系统中,有两种封装模板变量的类,一个是django.template.Context,这是最经常使用的,咱们在使用render_to_response方法的时候传入的第二个dictionary参数,就会被这个Context类封装一次,而后传到模板当中。前端
另外一个是django.template.RequestContext,它和Context类相比有两个不一样之处。python
第一个不一样的是,在生成一个RequestContext变量的时候,须要传入一个HttpRequest对象做为它的第一个参数。django
其次,它会增长一些自动注入模板的变量,这些变量由settings中的TEMPLATE_CONTEXT_PROCESSORS中声明的方法返回,TEMPLATE_CONTEXT_PROCESSORS中的方法都接收一个HttpRequest对象,最终return一个dict。这个dictionary里面的元素就会成为RequestContext中自动注入模板的变量。好比django.contrib.auth.context_processors.auth就会返回user、messages、perms变量json
# 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()这种操做,这是将当前域的全部局部变量都赋给dictionaryapi
HttpResponseapp
# django/http/response.py # HttpResponse的初始化 class HttpResponseBase(six.Iterator): def __init__(self, content_type=None, status=None, reason=None, charset=None): class HttpResponse(HttpResponseBase): def __init__(self, content=b'', *args, **kwargs): super(HttpResponse, self).__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content
python super(HttpResponse, self).__init__(*args, **kwargs)
Response框架
# rest_framework/response.py # Response的初始化 class Response(SimpleTemplateResponse): def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None):
若是要在函数式视图使用Response,须要加上@api_view装饰器,如函数
from rest_framework.decorators import api_view @api_view(['GET', 'POST', ]) def articles(request, format=None): data= {'articles': Article.objects.all() } return Response(data, template_name='articles.html')
若是不加装饰器的话,会报错:“.accepted_renderer not set on Response”rest