Search code examples
djangopermissionsdjango-rest-frameworkdjango-guardian

Django rest framework queryset custom permissions


I would like to set custom permissions with django guardian on my django rest framework views. I've successfuly achieved it for RetrieveModelMixin, but not for ListModelMixin.

I have a permission class looking like this one :

class CustomPerm(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated()

    def has_object_permission(self, request, view, object):
        if request.method == 'GET':
            if object.public is True:
                return True

            if object.user.is_staff is True:
                return True

            if 'read_object' in get_perms(request.user, object):
                return True

            return False

        if request.method == 'POST':
            #...

I also simplified the view here :

@authentication_classes((TokenAuthentication, SessionAuthentication, BasicAuthentication,))
@permission_classes((CustomPerm,))
class ObjectView(ListModelMixin,
                 RetrieveModelMixin,
                 viewsets.GenericViewSet):
    queryset = myObject.objects.all()
    serializer_class = ObjectSerializer

Behaviour I was naïvly expecting : ListModelMixin could filter by itself objects according to CustomPerm has_object_permission rules.

But it does not work like that. I'm able to do what I want by writing a get_queryset method and applying my custom permission rules, but it seems unappropriate and awful.

Is there a better way ? Thanks :)

PS: I'm sure I'm missing something and my question is naïve but I can't see what.


Solution

  • I'm afraid that the framework doesn't work that way ... The permissions are there to deny the access (when a condition is met), but not to filter the objects for you. If you need to return specific objects, then you need to filter them in the view (queryset) depending on the current user, if needed.