DRF——ViewSet权限使用

可以自定义权限的类,下面是拥有者权限的类

from rest_framework.permissions import BasePermission,SAFE_METHODS

class IsOwnerOrReadOnly(BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        return obj.user == request.user

登录才能访问的权限

from rest_framework.permissions import IsAuthenticated

class ModelViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):
    ...
    permission_classes =(IsAuthenticated,IsOwnerOrReadOnly)
    #设置RetrieveModelMixin查找的字段,id为url路径最后的参数
    lookup_field = "field_id"
    ...

猜你喜欢

转载自blog.csdn.net/qq_35037977/article/details/79772030