Mark Kiraly
Mark Kiraly

Reputation: 337

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)

Upvotes: 0

Views: 575

Answers (2)

Mike D Hovhannisyan
Mike D Hovhannisyan

Reputation: 434

If you use

class FilesView(ModelViewSet):

instead of

class FilesView(ListAPIView)

you can use get_serializer_class method which could help you For example

def get_serializer_class(self):
    if "your statement":
        return "FirstSerializer"
    if "your statement":
        return "SecondSerializer"

Upvotes: 0

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

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.

Upvotes: 2

Related Questions