renderers in Django Rest Framework

renderers in Django Rest Framework

Renderers are used to serialize the response into a specific media type like JSON, XML, YAML, etc. Django REST Framework provides various built-in renderer classes and it also supports to write a custom renderer. We specify renderers as an iterable type (i.e tuple, list, set, etc.). It means we can use multiple renderers for a single view/viewset. A renderer is chosen based on the media type received in the request. We can also specify default renderers globally in settings.

Setting renderers globally

We can set renderers globally like below in settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

Setting renderer for a View or Viewset

we can set renderer to a view or viewset using attribute "renderer_classes" like below.

from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
class UserCountView(APIView):
    """
    A view that returns the count of active users in JSON.
    """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)