Django - DRF - 響應器(渲染器)
阿新 • • 發佈:2018-12-29
目錄
1-3 form表單方式:HTMLFormRenderer - ?format=form
1-4 表格方式:AdminRenderer - ?format=admin
一、響應器顯示
1-1 預設顯示 - format=api
1-2 JSON格式顯示 format=json
1-3 form表單方式:HTMLFormRenderer - ?format=form
1-4 表格方式:AdminRenderer - ?format=admin
二、響應器的配置
2-1 區域性使用
from rest_framework.renderers import HTMLFormRenderer,BrowsableAPIRenderer class BookDetailView(APIView): renderer_classes = [HTMLFormRenderer,BrowsableAPIRenderer ] def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data) def put(self,request,pk): book_obj = models.Book.objects.filter(pk=pk).first() bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): models.Book.objects.filter(pk=pk).delete() return Response("")
2-2 全域性使用 - settings配置
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES':['rest_framework.renderers.JSONRenderer'] }
三、自定義顯示預設頁面
from rest_framework.renderers import TemplateHTMLRenderer class BookDetailView(APIView): renderer_classes = [TemplateHTMLRenderer] def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data,template_name='aa.html')