How to create permission for specific rules in Django Rest Framework?

别来无恙 提交于 2021-02-08 11:56:22

问题


I want to arrange permission like that each user can edit his own profile. Just super user can edit all profile. What I need to add permissions.py ? Thank you.

views.py

class UserViewSet(mixins.ListModelMixin,
              mixins.RetrieveModelMixin,
              mixins.UpdateModelMixin,
              mixins.DestroyModelMixin,
              generics.GenericAPIView):

queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
authentication_classes = (JSONWebTokenAuthentication, )

permissions.py

class IsOwnerOrReadOnly(BasePermission):

message = '!!'
my_safe_method = ['GET', 'PUT']

def has_permission(self, request, view):
    if request.method in self.my_safe_method:
        return True
    return False

def has_object_permission(self, request, view, obj):
    # member .0 Membership.objects.get(user=request.user)
    # member.is_active
    if request.method in SAFE_METHODS:
        return True
    return obj.user == request.user

回答1:


Write your own permission

class IsObjectOwner(BasePermission):
        message = "You must be the owner of this object."
        my_safe_methods = ['GET', 'PUT', 'PATCH', 'DELETE']

    def has_permission(self, request, view):
        if request.method in self.my_safe_methods:
            return True
        return False

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

and then in the view add it in permission_classes

class UserDetailView(RetrieveUpdateDestroyAPIView):
    permission_classes = [IsObjectOwner, permissions.IsAuthenticated]


来源:https://stackoverflow.com/questions/38867688/how-to-create-permission-for-specific-rules-in-django-rest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!