Search code examples
djangodjango-rest-frameworkdjango-permissions

DRF Viewset remove permission for detail route


I have a basic Viewset:

class UsersViewSet(viewsets.ModelViewSet):
    permission_classes = (OnlyStaff,)
    queryset = User.objects.all()
    serializer_class = UserSerializer

It is bind to the /api/users/ endpoint. I want to create a user profile page, so I need only a particular user, so I can retrieve it from /api/users/<id>/, but the problem is that I want /api/users/<id>/ to be allowed to anyone, but /api/users/ to keep its permission OnlyStaff, so no one can have access to the full list of users.

Note: Perhaps it's not such a good implementation, since anyone could brute force the data incremeting the id, but I'm willing to change it from <id> to <slug>.

How can I delete the permission from detail route?

Thanks in advance.


Solution

  • Override the get_permissions() method as below

    from rest_framework.permissions import AllowAny
    
    
    class 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()