Home > Back-end >  Isadminuser or Allowyany permission based on the request method in APIView
Isadminuser or Allowyany permission based on the request method in APIView

Time:09-24

I have to make a custom permission class based on the request method and the slug that has been passed. I am using APIView to write business logic. The requirements are as follows:

1. Allowany for all the methods except POST.

2. IsAdminUser for POST if slug is abc or Allowany if slug is xyz.

My view looks like this:

class Example(APIView):
    permission_classes = [CustomPermission]

    def get_by_slug(self, slug):
        return Example.objects.filter(slug=slug).first()

    def get(self, request, *args, **kwargs):

        slug = kwargs.get("slug")
        example = self.get_by_slug(slug)
        serializer = ABCSerializers(example)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):

        slug = kwargs.get("slug")
        setting = self.get_by_slug(slug)
        if slug == 'abc':
        ........................................
        /////////////////////////////////

For this, I have to define Custompermission which inherits from BasePermission

class CustomPermission(BasePermission):
    """
        returns permission based on the request method and slug
    """
    def has_permission(self, request, view):
        user =request.user
        if request.method == 'POST' and slugs == 'abc':
            return True

Now, I dont know how to get slug here. The slug here is acquired form **kwargs. But kwargs cant be defined inside has_permission. How can we do this??

CodePudding user response:

You can extract slug from request.data:

if request.method == 'POST' and request.data["slug"] == 'abc':
    return True
  • Related