[Fixed]-How to restrict Django Rest Framework browsable API interface to admin users


Is `DEFAULT_PERMISSION_CLASSES’ setting not enough? This sets a default restriction on all views DRF docs on default permission classes

In settings.py:


They will ‘reach’ the browsable interface but all types of requests will be denied if not authorized.

If for some reason various end-points needed to be reached by non-admin users, you could loosen the restriction on a view-by-view basis.


Assuming you’re using DRF’s built in views, I think you can just override get_renderers().

In your settings file:

    # Only enable JSON renderer by default.

And then in your views.py:

from rest_framework import generics, renderers

class StaffBrowsableMixin(object):
    def get_renderers(self):
        Add Browsable API renderer if user is staff.
        rends = self.renderer_classes
        if self.request.user and self.request.user.is_staff:
        return [renderer() for renderer in rends]

class CustomListApiView(StaffBrowsableMixin, generics.ListAPIView):
    List view.
    # normal stuff here


In rest_framework views we have a attribute called renderes_classes
Usually we have a method get_<something> as we do with queryset/get_queryset but in this case we didn’t have that, so i needed to implement a property.

from tasks.models import Task
from tasks.serializers import TaskSerializer

from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.renderers import CoreJSONRenderer

class CustomRendererView:
    permission_classes = (IsAuthenticatedOrReadOnly,)

    def renderer_classes(self):
        renderers = super(ListTask, self).renderer_classes

        if not self.request.user.is_staff:
            renderers = [CoreJSONRenderer]

        return renderers

class ListTask(CustomRendererView, ListAPIView):
    queryset = Task.objects.all()
    serializer_class = FullTaskSerializer

Leave a comment