2016-08-10 88 views
0

我想安排像每個用戶可以編輯他自己的配置文件的權限。只需超級用戶即可編輯所有配置文件我需要添加permissions.py?謝謝。如何在Django Rest Framework中爲特定規則創建權限?

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

寫自己的權限

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 

,然後在view它添加permission_classes

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

我在view.py中使用User = get_user_model()。因此,在這一行中返回obj.user_id == request.user有這樣的錯誤'User'對象沒有'user_id'屬性。我如何編輯它?謝謝。 – knkzlgc

+0

@knkzlgc,我編輯了我的答案。 –

+0

好的,謝謝。 – knkzlgc

相關問題