A. Atiyah
A. Atiyah

Reputation: 555

Setting different permission classes for POST and GET while using djangorestframework's default router

I was just watching some online tutorial on how to use Django Rest Framework to create a basic REST API using their default router. Link to Docs

but then because he used a model viewset he had to add permission_classes to them which means all different types of requests whether its post or get or others it'll all take the same permission.

I was wondering if there's a way to give them different permission_classes depending on the type of request.

Upvotes: 1

Views: 409

Answers (2)

asad_hussain
asad_hussain

Reputation: 2011

To achieve what you need, one possible solution is to override the get_permissions() of ViewSet.

def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == 'list':
            return [objects of permissions_u_need_in_list_view]

        elif self.action == 'create':
            return [objects of permissions_u_need_in_create_view]

This is what DRF provides the definition of get_permissions().

def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        return [permission() for permission in self.permission_classes]

Upvotes: 1

Yes, you can write your own permissions. Just create some python file. I named it permissions.py:

from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from company.models import Company


class IsGetOrIsAuthenticated(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET':
            return True
        return request.user and request.user.is_authenticated


class IsGetOrIsCompanyOwner(BasePermission):
    def has_permission(self, request, view):
        if request.method == 'GET' or 'OPTIONS':
            return True
        elif request.method == 'DELETE':
            company = get_object_or_404(Company, id=view.kwargs['pk'])
            return request.user.user_type == 'moder' or company.owner == request.user
        else:
            company = get_object_or_404(Company, id=view.kwargs['pk'])
            return company.owner == request.user or request.user.user_type == 'moder'


class IsModer(BasePermission):
    def has_permission(self, request, view):
        return request.user.user_type == 'moder'

After that you can use them in views.py

from company.permissions import IsGetOrIsAuthenticated, IsGetOrIsCompanyOwner, IsModer

class ActiveCompanyShortView(ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsGetOrIsAuthenticated,)

you can read more there

Upvotes: 2

Related Questions