I want to allow the get
for retriving a single object to the guest users. But keep the list
which retrives all items of that model in the database only for admins. But i am not sure how to seperate get
and list
because they both seem to be under the get
from my point of view.
Below is my viewset:
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
And my ReadOnly:
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
class ReadOnly(BasePermission):
def has_permission(self, request, view):
return request.method in SAFE_METHODS
CodePudding user response:
You can use get_permission
function and action
.
class OrdersViewSet(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated|ReadOnly]
serializer_class = OrderSerializer
queryset = Order.objects.all()
# parser_classes = (MultiPartParser,)
model = Order
def update(self, request, *args, **kwargs):
kwargs['partial'] = True
return super().update(request, *args, **kwargs)
def get_permissions(self):
if self.action == 'list':
permission_classes = [IsAdmin]
elif self.action == 'retrieve':
permission_classes = [AllowAny]
else:
permission_classes = [ReadOnly]
return [permission() for permission in permission_classes]