Using a permission class on a detail route

2019-04-05 14:43发布

How can I only apply a permission class to a detail route?

class EventViewSet(viewsets.ModelViewSet):

    @detail_route(methods=['post'])
    def messages(self, request, pk=None):
        ### Check a permissions class.
        ...

2条回答
姐就是有狂的资本
2楼-- · 2019-04-05 15:21

If you have a problem with permissions_classes in your custom actions in the ViewSet, try to use this decorator on your action. Probably the newest Django Rest Framework is not looking at permissions. Solution for this situation is to check it by yourself at the beggining of every custom action or to use following decorator:

def check_permissions(fun):
    def ref(self, request, pk=None):
        obj = get_object_or_404(self.get_queryset(), pk=pk)
        self.check_object_permissions(self.request, obj)

        return fun(self, request, pk)

    return ref
查看更多
祖国的老花朵
3楼-- · 2019-04-05 15:30

You can add permissions basically by doing this:

class EventViewSet(viewsets.ModelViewSet):
    @detail_route(
        permission_classes=[
            permissions.PermissionClass_],
        methods=['post'])
    def messages(self, request, pk=None):
        ### Check a permissions class.
        ...
查看更多
登录 后发表回答