1、作用
根据 用户请求URL 或 用户可接受的类型,筛选出合适的 渲染组件。
用户请求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json
2、内置渲染器
显示json格式:JSONRenderer
访问URL:
-
http://127.0.0.1:8000/test/?format=json http://127.0.0.1:8000/test.json http://127.0.0.1:8000/test/
默认显示格式:BrowsableAPIRenderer(可以修改它的html文件)
访问URL:
http://127.0.0.1:8000/test/?format=api http://127.0.0.1:8000/test.api http://127.0.0.1:8000/test/
表格方式:AdminRenderer
访问URL:
http://127.0.0.1:8000/test/?format=admin http://127.0.0.1:8000/test.admin http://127.0.0.1:8000/test/
form表单方式:HTMLFormRenderer
访问URL:
http://127.0.0.1:8000/test/?format=form http://127.0.0.1:8000/test.form http://127.0.0.1:8000/test/
3、局部使用
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("")
4、全局使用
4-1 settings.py中配置
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer'] }
5、自定义显示模块
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>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。