Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I check a custom permissions class to see if user has access, if not, a 403 is sent back.

However, I would like to attach the object ID so the user can click a button on the front-end to request access.

My current implementation is to override the retrieve method and "manually" check permission 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 method, has_perm returns a QuerySet of users instead of a boolean as defined in the permissions method. How come?

Is there a cleaner approach to this?

like image 406
WBC Avatar asked Sep 15 '14 18:09

WBC


Video Answer


1 Answers

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 no need to override retrieve method

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

 

like image 157
Venkatesh Bachu Avatar answered Sep 21 '22 19:09

Venkatesh Bachu