FACode FACode - 4 months ago 52
Python Question

Django Rest Framework owner permissions

I use Django Rest Framework and in my one of my viewsets class I have partial_update method (PATCH) for update my user profile. I want to create a permission for one user can update only his profile.

class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows profiles to be viewed, added,
deleted or edited
"""
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch']

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

def get_serializer_class(self):
if self.action == 'list':
return ListingMyProfileSerializer
if self.action == 'retrieve':
return ListingMyProfileSerializer
if self.action == 'update':
return ProfileSerializer
return ProfileSerializer

def get_permissions(self):
# Your logic should be all here
if self.request.method == 'GET':
self.permission_classes = (IsAuthenticated,)
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsOwnerOrReject)
return super(ProfileViewSet, self).get_permissions()

def partial_update(self, request, pk=None):
...
...


Now one user can update his profile and any other profile.
I tried to create a permission class: IsOwnerOrReject but I don't know exactly what I must to do.
Thanks for helping :D

SOLVED:

permissions.py class:

class IsUpdateProfile(permissions.BasePermission):

def has_permission(self, request, view):
# can write custom code
print view.kwargs
try:
user_profile = Profile.objects.get(
pk=view.kwargs['pk'])
except:
return False

if request.user.profile == user_profile:
return True

return False


views.py:

class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch', 'delete']
...

def get_permissions(self):
...
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsUpdateProfile)
return super(ProfileViewSet, self).get_permissions()

def partial_update(self, request, pk=None):
...

Answer

IsOwnerOrReject is permission class that match the user to current login user otherwise it rejects.

For ypu condition you have to define custom permission class.Which check user is login for other profile what ever permission you want to apply. You can do.

class IsUpdateProfile(permissions.BasePermission):

      def has_permission(self, request, view):
           #### can write custom code
           user = User.objects.get(pk=view.kwargs['id']) // get user from user table.
           if request.user == user:
              return True
           ## if have more condition then apply
           if more_condition:
              return True
           return False