根據用戶請求URL或用戶可接受的類型,篩選出合適的 渲染組件。
用戶請求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.jsonhtml
顯示json
格式:JSONRenderer
python
訪問URL:json
默認顯示格式:BrowsableAPIRenderer
(能夠修改它的html
文件)api
訪問URL:rest
表格方式:AdminRenderer
code
訪問URL:orm
**form
表單方式:HTMLFormRenderer**
htm
訪問URL:get
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("")
settings.py
中配置it
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')
<!DOCTYPE html> <html lang="en"> <head> <title>Title</title> </head> <body> {{ title }} {{ publishDate }} </body> </html>