Last Updated: February 25, 2016
·
1.821K
· paperaeroplain

Custom Media Type renderer for DjangoRestFramework

Django Rest Framework allows you to easily create custom output for content negotiation. To do this, we create a custom renderer which inherits from the Rest Framework BaseRenderer, and simply add this (paste in the whole section to settings if this is your first mod) to the list of REST FRAMEWORK > DEFAULT RENDERER CLASSES.

The following snippets show an example of creating a Tabbed Seperated Values (TSV) output which is created based on using defined meta data from the serializer class. Note: You don't have to use the serializer class in the renderer.

imagedata.serializers.imageserializer

from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from rest_framework import serializers
from imagedata.models import *

class ImageSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Image
        fields = ('id','elementUri','width','height','format','imagePath')

imagedata.renderers.tsvrenderer

from django.utils.encoding import smart_unicode
from rest_framework import renderers
from imagedata.serializers.imageserializer import ImageSerializer

class TsvRenderer(renderers.BaseRenderer):
    media_type = 'text/tab-separated-values'
    format = 'tsv'

    def render(self, data, media_type=None, renderer_context=None):

        # TSV format:
        # Column Names first row
        # Tab separated per row
        # Using Fields defined in the ImageSerializer to create fields and add values

        tabbedData = ''

        # Column names
        first = True
        for columnName in ImageSerializer.Meta.fields:
            if first == True:
                tabbedData = '%s' %(columnName)
                first = False
            else:
                tabbedData = '%s\t%s' %(tabbedData,columnName)

        tabbedData = '%s\n' %tabbedData

        # Column values
        first = True
        for lineItem in data:
            for columnName in ImageSerializer.Meta.fields:
                if first == True:
                    tabbedData = '%s%s' %(tabbedData,lineItem[columnName])
                    first = False
                else:
                    tabbedData = '%s\t%s' %(tabbedData,lineItem[columnName])

            tabbedData = '%s\n' %tabbedData
            first = True

        return tabbedData

settings.py

# Conneg preference order
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'imagedata.renderers.TsvRenderer',
    )
}