未为详细信息和列表视图调用 Django Rest Framework 权限

Django Rest Framework Permissions not being called for Detail and List View

我创建了这个自定义权限 class,当我从视图发出请求时它似乎没有被调用。我事件将其设置为 return false 并且请求仍然成功。尝试放置打印语句以查看是否有任何输出但没有。不知道我在做什么。

查看:

class EventEditView(RetrieveUpdateDestroyAPIView):
    authentication_classes = (SessionAuthentication, JSONWebTokenAuthentication,  )
    permission_classes = (EventVisibilityPerm, )
    serializer_class = EventEditSerializer

    def get(self, request, *args, **kwargs):
        event = get_object_or_404(Event, slug=kwargs['slug'])
        serializer = EventSerializer(event)
        return Response(serializer.data)

Permissions.py:

class EventVisibilityPerm(permissions.BasePermission):
    """
    Permission class determines whether a user has access to a specific Event
    """

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

**序列化器:**

class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        exclude = ('user', 'id')

目前正在测试此详细视图的权限,但此权限也需要在列表视图上使用。

必须在创建自定义权限时实施has_permission(self, request, view)方法类 .

来自DRF Doc,

The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed.

示例:

from rest_framework import permissions


class EventVisibilityPerm(permissions.BasePermission):
    <b>def has_permission(self, request, view):
        """
        allowing users with specific email ids
        """
        if request.user.email in EMAIL_WHITELIST:
            return True
        return False</b>

    def has_object_permission(self, request, view, obj):
        """
        allowing users those who are the owner of the object (obj.user)
        """
        return request.user == obj.user

您可以为权限 class 覆盖两个函数,您继承自 BasePermission。这些函数是 has_permissionhas_object_permissionhas_permission 被自动选中。但是 has_object_permission 函数应该在您的视图中使用以下代码手动调用:

self.check_object_permissions(self.request, obj)