Reputation: 472
I have set permission to the update method to allow only the Admin user to update the user info but for some reasons when I logged in as normal user I can also update the user info. What can I do to avoid that? other methods work just fine.
class CustomUserViewSet(viewsets.ModelViewSet):
queryset = models.CustomUser.objects.all()
serializer_class = serializers.CustomUserSerializer
parser_classes = [JSONParser]
permission_classes_by_action = {
'create': [IsAdminUser], 'list': [IsAdminUser], 'retrieve': [IsAuthenticated],
'update': [IsAdminUser], <--already set here
'destroy': [IsAdminUser,]
}
def update(self, request, *args, **kwargs):
return super(CustomUserViewSet, self).update(request, *args, **kwargs)
# some other methods
def get_permissions(self):
try:
# return permission_classes depending on `action`
return [permission() for permission in self.permission_classes_by_action[self.action]]
except KeyError:
# action is not set return default permission_classes
return [permission() for permission in self.permission_classes]
Upvotes: 0
Views: 548
Reputation: 88569
In DRF ViewSets, the HTTP PATCH method is mapped with action name partial_update
. So you have to update the permission_classes_by_action
attribute as
permission_classes_by_action = {
'create': [IsAdminUser],
'list': [IsAdminUser],
'retrieve': [IsAuthenticated],
'update': [IsAdminUser],
'partial_update': [IsAdminUser],
'destroy': [IsAdminUser, ]
}
Upvotes: 1