[Django]-Django DRF – Restrict Access to List View via Permissions

9👍

class CanViewAndEditStaff(permissions.BasePermission):

    def has_permission(self, request, view):

        # IF THIS IS A LIST VIEW, CHECK ACCESS LEVEL
        if (view.action == 'list' and request.user.access_level < 3 ):
            return True

        # ELSE, CONTINUE ON TO OBJECT PERMISSIONS

you can use view.action to know if this is list or something else.

👤Ykh

0👍

This doesn’t exactly address the question, but this technique is applicable.

I used a variation on Ykh’s answer that allows the same permission class to be used broadly across many views which display a variety of different models.

In my view class I added an attribute to distinguish the originating view, thus allowing the appropriate object comparison to determine permissions

# views.py
class SomeView(ListAPIView):
    permission_classes = (IsPermd, )
    is_some_view = True

class SomeOtherView(RetrieveAPIView
    permission_classes = (IsPermd, )
    is_some_other_view = True

# permissions.py
class IsPermd(BasePermission):
    def has_object_permissions(self, request, view, obj):
        if hasattr(view, 'is_some_view'):
            # whatever special considerations
        if hasattr(view, 'is_some_other_view'):
            # whatever other special considerations

This feels a little clunky, but until I find a better way I’ll stick with it.

Leave a comment