[Django]-Permissions checking in serializer, Django rest framework,

5👍

You can write a custom permission class HasWritePermissions which will check whether a user has write/update permissions.

To create a custom permission class, you will need to override BasePermission class and implement has_permission() method. This method should return True if request is to granted access, otherwise False.

class HasWritePermissions(BasePermission):

    def has_permission(self, request, view):
        # grant access to non-create/update requests
        if request.method not in ['POST', 'PUT', 'PATCH']:
            return True

        # grant access if user is a member of organization of the object 
        # to be modified or is a coordinator
        if (organization in user.organizations) or (user_is_a_coordinator):
            return True

        # Otherwise don't grant access
        return False 

Leave a comment