So I've seen a couple of questions here on SO which are similar, but not quite what I'm looking for.
I'm trying to have different permissions per method within the same view. What I currently have:
class MyViewSet(viewsets.ViewSet):
# User must be authenticated
permission_classes = (IsAuthenticated,)
def list(self, request):
...
# User must be admin
def create(self, request):
...
def retrieve(self, request):
...
Basically I'm trying to ensure that only admins can call the create
method. I've looked at creating custom permissions, but that applies accross the viewset, which is not quite what I want.
I think there is no inbuilt solution for that. But you can achieve this by overriding the get_permissions
method.
class MyViewSet(viewsets.ViewSet):
permission_classes_by_action = {
"default": [IsAuthenticated],
"retrieve": [AllowAny],
}
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_by_action["default"]
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With