限制用户访问APIView

时间:2018-01-16 09:20:15

标签: python django django-rest-framework

我想获取用户的详细信息:

class UserDetailAPIView(RetrieveAPIView):
    """
    User detail information
    """
    queryset = User.objects.filter(is_valid=True).exclude(status=4)
    serializer_class = UserDetailSerializer
    lookup_field = "username"

我想限制其他用户访问此APIView,我只希望管理员用户和自己的用户访问它。

如何限制?

1 个答案:

答案 0 :(得分:1)

你应该定义自己的权限类。像这样:

from rest_framework import permissions


class OwnerProfilePermission(permissions.BasePermission):
    """object lvl permissions for owner """
    def has_object_permission(self, request, view, obj):
        return obj.user == request.user

并在您的观看中包括permission_classes。请参阅DRF文档。 http://www.tomchristie.com/rest-framework-2-docs/api-guide/permissions

您选择的类库视图很重要。 http://www.tomchristie.com/rest-framework-2-docs/api-guide/generic-views