Add a @permission_class decorator on a ModelViewSet

1,275 views
Skip to first unread message

Martín Freytes

unread,
Oct 20, 2015, 5:08:57 PM10/20/15
to Django REST framework
I need to add a permission on a list from a viewsets.ModelViewSet.

I like to use that with the decorator: @permission_classes([permissions.IsAuthenticated, ]) because I'm overriding get_permissions

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        if permissions.IsAuthenticated in self.permission_classes:
            return (permissions.IsAuthenticated(),)

        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(),)

    @permission_classes([permissions.IsAuthenticated,])
    def list(self, request, *args, **kwargs):
        user = request.user
        if user.is_admin:
            return super(UserViewSet, self).list(request, *args, **kwargs)

        serialized_user = self.serializer_class(user)
        return Response(serialized_user.data, status=status.HTTP_200_OK)

This is not giving 401 when the user is unauthenticated. Instead I'm receiving: 'AnonymousUser' object has no attribute 'is_admin'

Aart Goossens

unread,
Oct 23, 2015, 7:05:44 AM10/23/15
to Django REST framework
I am not sure if it can fix your problem entirely, but take a look at Authentication - Django Rest Framework.

Op dinsdag 20 oktober 2015 23:08:57 UTC+2 schreef Martín Freytes:

Xavier Ordoquy

unread,
Oct 23, 2015, 7:48:57 AM10/23/15
to Django REST framework
Hi Martin,

The decorator will only work on pure functions and it'll create an APIView behind the scene.
You can work this around by checking the action type within the get_permission method.

Regards,
Xavier,
Linovia.
Reply all
Reply to author
Forward
0 new messages