Home > database >  How to apply permissions on perform_create in ViewSet DRF
How to apply permissions on perform_create in ViewSet DRF

Time:01-19

This is my View Set:

class MyViewSet(ModelViewSet):
    serializer_class = MySerializer
    queryset = MyClass.objects.all()

   def get_serializer_class(self):
        if self.request.user.is_superuser:
            return self.serializer_class 

        return serializers.MyUserSerializer   

    def perform_create(self, serializer):
        employee = models.Employee.objects.get(user=self.request.user)
        serializer.save(employee=employee)

I want to apply permission before perform_create, this perform_create() should only be called if a currently logged in user is not a super user. If a currently logged in user is a superuser, default perform_create function should be called.

How to do that?

CodePudding user response:

You can use permission_classes in your Viewset class

from rest_framework.permissions import IsAuthenticated
class MyViewSet(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = MySerializer
    queryset = MyClass.objects.all()

    ...

CodePudding user response:

Try this logic

def perform_create(self, serializer):
  self.request.data.get("title", None)  # read data from request
  if self.request.user.is_authenticated and not self.request.user.is_superuser:
      instance = serializer.save(author=self.request.user)
  else:
      instance = serializer.save() 

CodePudding user response:

Try like this:

class MyViewSet(ModelViewSet):
    serializer_class = MySerializer
    queryset = MyClass.objects.all()

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return self.serializer_class 

        return serializers.MyUserSerializer   

    def perform_create(self, serializer):
        employee = models.Employee.objects.get(user=self.request.user)
        serializer.save(employee=employee)

    def has_permission(self, request, view):
        if request.user.is_superuser:
            return True
        return super().has_permission(request, view)

perform_create method will be called only then if the user is not a superuser and have permissions. has_permission method will returns True for superusers.

  • Related