0

Suppose that I have a Viewset named UserViewset, and I have assigned IsAuthenticated permission to UserViewset Viewset. Now, I want to create a normal method (not an action method), and I want to assign another permission to that method which is IsAdminUser, how would I do that?

Below is the code with the method which I tried:

from rest_framework.viewsets import GenericViewSet
from rest_framework.permissions import IsAuthenticated, IsAdminUser

class UserViewset(GenericViewSet):
    permission_classes = (IsAuthenticated,) # THIS IS THE DEFAULT PERMISSION I HAVE SET FOR THIS VIEWSET WHICH WILL APPLY TO ALL METHODS OR ACTION METHODS
    
    def create(self, *args, **kwargs): # THIS IS MY CUSTOM METHOD
        permission_classes = (IsAuthenticated, IsAdminUser) # I WANT SOMETHONG LIKE THIS, BUT IT DOES NOT WORK
        .
        .
        .
  • Check this question, see if it's what you need. https://stackoverflow.com/questions/19773869/django-rest-framework-separate-permissions-per-methods – Jovan V Nov 19 '22 at 01:48
  • @JovanVuchkov thank you for the giving the direction. The answer of GDorn was a perfect solution to my problem. – Khubaib Khawar Nov 19 '22 at 14:50
  • Well, I just checked and it was for action methods, not normal methods, so it has still not solved my issue. – Khubaib Khawar Nov 19 '22 at 15:20

1 Answers1

0

You can override get_permission class

 def get_permissions(self):
    # check the action and return the permission class accordingly
    if self.action == 'create':
        return [IsAdminUser(),]
    return [IsAuthenticated(), ]
  • this will only work for action methods, not normal methods. You can see that `create()` is a normal method in my Viewset, it does not have `@action` decorator. So, can you suggest something to use custom permissions for a normal method of a Viewset? – Khubaib Khawar Nov 19 '22 at 15:22