I have a Modelviewset class that has several functions inside it like list(), destroy, partial_update() and also other custom functions like def get_examples(self,request)
. The thing is different functions have different permissions based on the user types. I have a separate permission class inside a permission file. Now I need to access the action inside the has_permission function. I know it can be done inside the get_permission function inside modelviewset class. But how can we do it inside has_permission function??
My View:
class ExampleView(viewsets.ModelViewSet):
queryset = Example.objects.all().order_by("-created_at")
serializer_class = ExampleSerializer
pagination_class = ExampleNumberPagination
def list(self, request, *args, **kwargs):
def partial_update(self, request, *args, **kwargs):
def custom_fuctin_1(self,request,*args,**kwargs):
def custom_fuctin_2(self,request,*args,**kwargs):
def destroy(self, request, *args, **kwargs):
Now permission file:
class ExampleClassPermission(BasePermission):
def has_permission(self, request, view):
user =request.user
if request.method == 'GET' or request.method == 'POST':
return True
elif request.method == 'DELETE' and (user.role == 'manager' or user.role == 'admin'):
return True
elif request.method == 'PUT':
return True
else:
return False
Here in this permission class, I want to set permission for custom function_1 and 2 in the view class. I cant do self.action == ''? just like in the get_permission.Can I??
CodePudding user response:
You can access action by using view
argument:
class ExampleClassPermission(BasePermission):
def has_permission(self, request, view):
if view.action == 'list':
# your code here