How to return data with 403 error in Django Rest Framework?

When a GET request is sent to the API backend at /obj/1

I check my own permission class to see if the user has access, if not, 403 is sent back.

However, I would like to add an object identifier so that the user can click a button on the interface to request access.

My current implementation is to override the retrieve method and manually verify there.

Simplified Permissions

 class CustomPerm(...): def has_object_permission(...): return request.user.is_staff 

Viewset

 class CustomViewSet(...): model = Model permission_classes = (CustomPerm, ) def retrieve(self, request, pk=None): obj = get_object_or_404(Model, pk=pk) has_perm = CustomPerm().has_object_permission(request, self, obj=obj) if not has_perm: data = { 'id': obj.id } return Response(data, status=403) return super(ModelViewSet, self).retrieve(request, pk=pk) 

So, my current has_perm method returns a QuerySet for users instead of a boolean as defined in the permissions method. Why?

Is there a cleaner approach to this?

+6
source share
1 answer
 from rest_framework import permissions from rest_framework.exceptions import PermissionDenied class CustomPerm(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.user.is_staff: return True raise PermissionDenied({"message":"You don't have permission to access", "object_id": obj.id}) 

and you do not need to override the retrieve method

 class CustomViewSet(...): model = Model permission_classes = (CustomPerm, ) 

+16
source

Source: https://habr.com/ru/post/975317/


All Articles