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的區別
-
HttpResponse
# 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
- HttpResponse對象由Django創建,常用於函數式視圖
- super()常用於調用父類的方法。
即調用HttpResponse父類HttpResponseBase的__init__方法super(HttpResponse, self).__init__(*args, **kwargs)
- 因此,HttpResponse生成格式為HttpResponse(content=響應體, content_type=響應體數據類型, status=狀態碼)
- 注意如果前端需要json數據類型,而data是一個字典,則需要手動把data轉為json格式。HttpResponse(json.dumps(data))
-
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對象是Django REST framework框架封裝的對象
-
Response會自動將傳入data的數據轉為json,無需手動轉換。甚至可以直接Response(data=serializer.data)
-
一般在DRF框架中類的視圖中使用Response對象,類的視圖要繼承APIView
-
如果要在函數式視圖使用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”
-