一、作用:
根据用户的请求url或者用户可接受的类型、筛选出合适的渲染组件
用户请求url:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json
二、内置渲染器
显示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/
三、局部使用
设置路由:
url(r'^publish/(?P<pk>d+)/',views.PublishDetailView.as_view()),
设置视图:
from rest_framework.renderers import HTMLFormRenderer,BrowsableAPIRenderer class PublishDetailView(APIView): renderer_classes = [HTMLFormRenderer,BrowsableAPIRenderer] def get(self,request,pk): publish_list=models.Publish.objects.filter(pk=pk).first() ps=PublishSerializers(publish_list,many=False) return Response(ps.data) def put(self,request,pk): publish_list = models.Publish.objects.filter(pk=pk).first() ps=PublishSerializers(data=request.data,instance=publish_list) if ps.is_valid(): ps.save() # update return Response(ps.data) else: return Response(ps.errors) def delete(self,request,pk): models.Publish.objects.filter(pk=pk).delete() return Response("")
浏览器访问(默认):
加上html样式渲染:
四、全局使用:
在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')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ title }} {{ publishDate }} </body> </html>