Search code examples
pythondjangodjango-rest-frameworkrenderer

Define & Use Custom renderer Django Rest Framework View


I'm trying to override a CSV renderer import for a django rest framework view. Here's how so:

class CustomCSVRenderer(BaseCSVRenderer):
   def render():
      do something

   def tablize():
      do something

I've defined the CustomCSVRenderer in the same python class views.py as the view in question:

class MyView(ListAPIView, CustomMixinSet):

    renderer_classes = (CustomRenderer, JSONRenderer)

When I try to debug this implementation, my pdb debugger never hits the CustomCSVRenderer and instead I get a response based on some underlying renderer used by django restframework.

What could be the issue? How do I know what renderer django rest framework is using?


Solution

  • As @Daniel Roseman stated in the comment section, you'll need to do a little bit more in order to make this custom renderer work.

    From the docs:

    To implement a custom renderer, you should override BaseRenderer, set the .media_type and .format properties, and implement the .render(self, data, media_type=None, renderer_context=None) method.

    Thus, your CustomCSVRenderer should look like this:

    class CustomCSVRenderer(BaseCSVRenderer):
        media_type = 'text/csv'
        format = 'csv'
    
        def render(self, data, media_type=None, renderer_context=None):
           ...