Django Rest Framework: Output in JSON to the browser by default

Viewed 5512

I do not want to write ?format=JSON in the URL. It should return JSON by default with djangorestframework

3 Answers

@Devasish gives a default for all views, but you can also set the renderers used for an individual view, or viewset, as in the following example from the DRF doco:

APIView class-based views.

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)
Related