How to change permission based on request.query_params in Django rest frameworks?
I merged together two views that almost does the same thing except the permission, I want to change permission based on: if company id is in the params. If not, it would use a simple IsAuthenticated class and also created a permission for IsCompany.
class FilesView(ListAPIView):
serializer_class = FileSerializer
permission_classes = (IsAuthenticated,)
...
def get_queryset(self):
if 'company' in self.request.query_params:
# In this case I want the IsCompany Permission class
return get_company_files(self)
# Otherwise the regular one
return get_personal_files(self)
See custom permissions at DRF documentations.
A little example:
from rest_framework import permissions
class IsCompanyRequestBasedPermission(permissions.BasePermission):
message = '<description of your permission>'
def has_permission(self, request, view):
if 'company' in self.request.query_params:
# Make your decision.
And then add it to permission_classes
. It would work just as you expect.