Search code examples
djangodjango-rest-frameworkdjango-permissions

How to check if a requested user has a specific custom permission in Django Rest Framework?


I want to check with a boolean answer of True/False if a requested user has a permission defined in permissions.py.

More in particular, I want to check if the requested user has the permission of IsDriver. Is somehow possible?

class ExampleViewSet(viewsets.ModelViewSet):
    permission_classes = [IsChargingStationOwner |IsDriver | IsReadOnlyStations]
    serializer_class = ExampleSerializer

    def get_queryset(self):
        # get the request user
        requested_user = self.request.user
        if requested_user.is_anonymous :
            print('1')
        elif requested_user .... :
            print('2')

My question has to do with the elif statement.


Solution

  • Create a custom permission class that inherits

    rest_framework.permissions.BasePermission

    check DRF Permission docs here

    and if you want to recall it again inside any method you can use @gtopal approach:

    elif IsDriver().has_permission(self.request, self):
         print('2')