Jbb
Jbb

Reputation: 623

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.

Upvotes: 1

Views: 2656

Answers (2)

Roba
Roba

Reputation: 688

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.

Upvotes: 3

user2021091
user2021091

Reputation: 571

Well overriding isn't awful depending on how you do it... but it is not the question.

If I understand well what you want to do is to filter your queryset using your custom permission.

What I recommend, to keep your code explicit and simple, override your backend filter like in the doc

But be careful filter_queryset apply on both retrieve and list methods

Upvotes: 0

Related Questions