Home > Blockchain >  render class overiding the class method in apiview
render class overiding the class method in apiview

Time:10-10

I am a bit confused I want to render HTML or JSON by checking the accept header of the client but as I have specified the default render class,it is still rendering as per render class regardless of what Accept header is

class HomeView(APIView):
        template_name = 'blog_app/home.html'
        renderer_classes = [TemplateHTMLRenderer]
    
    
        def get(self,request):
            context = os.getcwd()
            print(request.headers['Accept'])
            if 'text/html'in request.headers['Accept']:
                
                return Response({'dir':context},template_name=self.template_name)
            else:
                return Response({'dir':context},content_type='json')
        

CodePudding user response:

You should override get_renderers function.

class HomeView(APIView):
        template_name = 'blog_app/home.html'
        renderer_classes = [TemplateHTMLRenderer]

        def get_renderers(self):
            if 'text/html'in request.headers['Accept']:
                self.renderer_classes = (TemplateHTMLRenderer,)
            else:
                self.renderer_classes = (JSONRenderer,)
        return super().get_renderers()
    
        def get(self,request):
            context = os.getcwd()
            return Response({'dir':context})
  • Related