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