我有以下观点:

class ActivityViewSet(viewsets.ModelViewSet):
    queryset = Activity.objects.all()
    serializer_class = ActivitySerializer

    def get_permissions(self):
        if self.action in ['update','partial_update','destroy','list']:
            self.permission_classes = [permissions.IsAdminUser,]
        elif self.action in ['create']:
            self.permission_classes = [permissions.IsAuthenticated,]
        else :
            self.permission_classes = [permissions.AllowAny,]
        return super(self.__class__, self).get_permissions()


如图所示,我试图为Authenticated用户(不是管理员)允许'create'方法而不允许'list'。
奇怪的是,此Viewset不会为Authenticated用户创建或列出任何结果。
我检查了一下,以清除以下代码:

class RouteOrderingDetail(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.UpdateModelMixin,
                   viewsets.GenericViewSet):
    queryset = RouteOrdering.objects.all()
    serializer_class = RouteOrderingSerializer


这确实允许在其中创建但没有列表的视图(但它对我不可用,因为我确实需要可用的列表选项。

希望问题解决。任何帮助将被申请。

最佳答案

也许您可以尝试以下方法:

class NotCreateAndIsAdminUser(permissions.IsAdminUser):
    def has_permission(self, request, view):
        return (view.action in ['update', 'partial_update', 'destroy', 'list']
                and super(NotCreateAndIsAdminUser, self).has_permission(request, view))


class CreateAndIsAuthenticated(permissions.IsAuthenticated):
    def has_permission(self, request, view):
        return (view.action == 'create'
                and super(CreateAndIsAuthenticated, self).has_permission(request, view))

class NotSafeMethodAndAllowAny(permissions.AllowAny)
    def has_permission(self, request, view):
        return (view.action is not in ['update', 'partial_update', 'destroy', 'list', 'create']
                and super(NotSafeMethodAndAllowAny, self).has_permission(request, view))


class ActivityViewSet(viewsets.ModelViewSet):
    queryset = Activity.objects.all()
    serializer_class = ActivitySerializer
    permission_classes = (NotCreateAndIsAdminUser, CreateAndIsAuthenticated, NotSafeMethodAndAllowAny)

    def create(self, request):
        pass

    def list(self, request):
        pass
    ....


参考:Allow separate permissions per View in ViewSet

另外,您可能想检查一下与您的问题非常相似的问题:Separate permissions per methods

要么

您可以这样做:

class ActivityViewSet(viewsets.ModelViewSet):
    queryset = Activity.objects.all()
    serializer_class = ActivitySerializer

    def get_permissions(self):
        if self.action in ['update', 'partial_update', 'destroy', 'list']:
            # which is permissions.IsAdminUser
            return request.user and request.user.is_staff
        elif self.action in ['create']:
            # which is permissions.IsAuthenticated
            return request.user and is_authenticated(request.user)
        else :
            # which is permissions.AllowAny
            return True

10-05 21:04