0

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??

Reactoo
  • 916
  • 2
  • 12
  • 40

2 Answers2

1

You can extract slug from request.data:

if request.method == 'POST' and request.data["slug"] == 'abc':
    return True
kamran890
  • 762
  • 4
  • 7
  • hello, sorry I clicked the answer correct. The issue is there is no any slugs in the body rather than coming in the url. SO how to acquire slug that is coming in the url?? – Reactoo Sep 24 '21 at 11:54
1

We can extract slug from request object in these type of functions like this:

 slug = request.resolver_match.kwargs["slug"]

OR

 slug = request.resolver_match.kwargs.get("slug")
Reactoo
  • 916
  • 2
  • 12
  • 40