DRF Viewset remove permission for detail route DRF Viewset remove permission for detail route django django

DRF Viewset remove permission for detail route


Override the get_permissions() method as below

from rest_framework.permissions import AllowAnyclass UsersViewSet(viewsets.ModelViewSet):    permission_classes = (OnlyStaff,)    queryset = User.objects.all()    serializer_class = UserSerializer    def get_permissions(self):        if self.action == 'retrieve':            return [AllowAny(), ]                return super(UsersViewSet, self).get_permissions()


It would help if you posted the permission class.

But going off what you posted, it appears that only staff users can have access to the endpoints bound to that viewset. Meaning no other user type/role can access those endpoints.

Going off your question, it seems like you want to setup a IsOwnerOrStaffOrReadOnly permission and over ride the list route function of the ModelViewSet and replace permission_classes and then call super

class UsersViewSet(viewsets.ModelViewSet):    permission_classes = (IsOwnerOrStaffOrReadOnly,)    queryset = User.objects.all()    serializer_class = UserSerializerdef list(self, request, *arg, **kwargs):   self.permission_classes = (OnlyStaffCanReadList,)   super(UsersViewSet, self).list(request, *args, **kwargs)  // python3 super().list(request, *args, **kwargs)

is Owner object permission class

class IsOwnerOrStaffOrReadOnly(permissions.BasePermission):    def has_object_permission(self, request, view, obj):        # Read permissions are allowed to any request,        # so we'll always allow GET, HEAD or OPTIONS requests.        if request.method in permissions.SAFE_METHODS:            return True        if request.user.role == 'staff':            return True        # Instance must have an attribute named `owner`.        return obj.owner == request.user

only staff can read permission class

class OnlyStaffCanReadList(permissions.BasePermission):    def has_object_permission(self, request, view, obj):        if request.user.role == 'Staff':            return True        else:           return False

as provided in the comments, your user model must have the owner role. if you are using the django user model you can just do a obj.id == request.user.id comparison