Django:如何限制对其所有者的模型列表访问权限?

时间:2017-06-19 08:31:04

标签: django django-models django-rest-framework django-authentication

我有一个django模型,我希望该模型只能由其所有者(创建模型的用户)访问。所以我创建了一个权限类,如下所示

class IsOwnerOnly(permissions.BasePermission):


def has_object_permission(self, request, view, obj):

    # Write permissions are only allowed to the owner of the snippet.
    return obj.owner == request.user

并在modelviewset上应用此权限

class ItemViewSet(viewsets.ModelViewSet):

    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = (IsOwnerOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

访问单个项目时,它可以工作,但即使这样,每个经过身份验证的用户都可以访问项目列表。那么我怎样才能将项目访问权限仅限于其所有者?

我在设置页面中包含了Tokenauthentication,如图所示

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (

    'rest_framework.authentication.TokenAuthentication',

),
}

,该项目看起来像

class Item(models.Model):

    name=models.CharField(max_length=30)
    address=models.TextField()
    owner = models.ForeignKey('auth.User', related_name='items', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

2 个答案:

答案 0 :(得分:0)

您无法控制谁可以按所有者访问项目列表,如果您需要,您需要将has_permission覆盖到类IsOwnerOnly,例如:

class IsAuthenticatedOwner(permissions.BasePermission):
    def has_permission(self, request, view):
        # work when your access /item/
        if request.user and is_authenticated(request.user):
            if request.user.id in [1, 2, 3]:
                return True
            else:
                return False
        else:
            return False

    def has_object_permission(self, request, view, obj):
        # work when your access /item/item_id/
        # Instance must have an attribute named `owner`.
        return obj.owner == request.user

注意:当您的访问has_permission(列表),/item/访问has_object_permission(检索和更新)时,/item/item_id/可以正常工作。

如果您想让用户只看到他创建的项目,简单如下:

class ItemsViewSet(ModelViewSet):
    queryset = Items.objects.all()
    serializer_class = ItemsSerializer
    permission_classes = (IsAuthenticated)

    def get_queryset(self):
        queryset = self.get_queryset().filter(owner=self.request.user)
        return queryset

答案 1 :(得分:0)

您可以在视图上覆盖方法get_queryset

class ItemViewSet(viewsets.ModelViewSet):

    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = (IsOwnerOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def get_queryset(self):
        return self.queryset.filter(owner=self.request.user)

这样,方法list(来自ModelViewSet)将调用您的“ get_queryset”以建立数据的分页。