DRF自定义权限未触发

时间:2020-04-10 17:43:04

标签: django django-rest-framework permissions

我为drf项目编写了一个自定义权限类,以保护我的视图:

views.py

class Employee(APIView):
    permission_classes = [BelongsToClient]
    serializer_class = EmployeeSerializer

    def get(self, request, pk, format=None):
        employee = EmployeeModel.objects.get(pk=pk)
        serializer = EmployeeSerializer(employee, many=False)
        return Response(serializer.data)

    def delete(self, request, pk, format=None):
        employee = EmployeeModel.objects.get(pk=pk)
        employee.Employees_deleted = True
        employee.save()
        return Response(status=status.HTTP_200_OK)

我的权限等级:

permission.py

from rest_framework import permissions

class BelongsToClient(permissions.BasePermission):
    message= "You are only authorized to view objects of your client"

    """
    Object-level permission to only see objects of the authenticated users client
    """

    def has_object_permission(self, request, view, obj):
        if obj.Mandant == request.user.Mandant:
            return True
        else:
            return False

不幸的是,即使在应该的情况下,此权限类也不会阻止我的视图。我不知道为什么。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

您需要在对APIView进行响应之前调用check_object_permissions方法

class Employee(APIView):
    permission_classes = [BelongsToClient]
    serializer_class = EmployeeSerializer

    def get(self, request, pk, format=None):
        employee = EmployeeModel.objects.get(pk=pk)
        serializer = EmployeeSerializer(employee, many=False)
        self.check_object_permissions(request, employee)
        return Response(serializer.data)

答案 1 :(得分:1)

has_object_permission仅在使用DestroyAPIViewRetrieveAPIViewViewSet时调用。

尝试使用如下所示的视图集

from rest_framework import viewsets

class Employee(viewsets.ViewSet):
    permission_classes = [BelongsToClient]
    serializer_class = EmployeeSerializer

    def delete(self, request, pk, format=None):
        employee = EmployeeModel.objects.get(pk=pk)
        self.check_object_permissions(request, employee)
        employee.Employees_deleted = True
        employee.save()
        return Response(status=status.HTTP_200_OK)

注意:我没有测试它,但是它应该可以工作。