Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the Django REST framework, how are the default permission classes combined with per-view(set) ones?

I'm reading http://www.django-rest-framework.org/api-guide/permissions/ and trying to relate it to the OAuth2 toolkit documentation, http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html. The latter has an example in which in settings.py one specifies

REST_FRAMEWORK = {
    # ...

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

and in addition, IsAuthenticated is also specified added to the permission_classes list of a ModelViewSet:

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = User.objects.all()
    serializer_class = UserSerializer

Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

like image 838
Kurt Peek Avatar asked Jan 29 '18 22:01

Kurt Peek


3 Answers

In the Django REST framework, how are the default permission classes combined with per-view(set) ones?

They are not combined.

... the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

Correct.

like image 124
wim Avatar answered Nov 12 '22 02:11

wim


Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it?

The DEFAULT_PERMISSION_CLASSES are used for views/viewsets where permission_classes is not defined. In the cases they are defined, those are used instead, not the default ones.

like image 40
dukebody Avatar answered Nov 12 '22 04:11

dukebody


If you do want to extend the default permissions, this seems to work.

Disclaimer: I found it by looking into DRF's code, not sure it is documented.

from rest_framework.settings import api_settings

class UserViewSet(viewsets.ModelViewSet):
    permission_classes = [*api_settings.DEFAULT_PERMISSION_CLASSES, TokenHasReadWriteScope]
like image 32
Arnaud P Avatar answered Nov 12 '22 04:11

Arnaud P