没有为自定义API调用has_object_permission

时间:2017-01-05 11:26:44

标签: python django django-rest-framework

我有一个用于API POST /api/samples/sample_id/check的视图集SampleViewSet。我为它定义了对象级别权限。

class SamplePermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        return True

class SampleViewSet(viewsets.ModelViewSet):
    permission_classes = (SamplePermission, )

    @detail_route(methods=['post'])
    def check(self, request, pk=None):
        if pk:
            print "check"

调用API POST /api/samples/check时,未调用函数has_object_permission。可能是什么原因?

1 个答案:

答案 0 :(得分:1)

权限不起作用,因为方法check_object_permissionsget_object函数中调用。因此,您应该在check函数中调用其中一个函数:

    @detail_route(methods=['post'])
    def check(self, request, pk=None):
        obj = self.get_object()
        ....

或者您可以直接在detail_route

中添加权限
    @detail_route(
    permission_classes=[SamplePermission],
    methods=['post'])
    def check(self, request, pk=None):
        ...