Django REST Framework - Separate permissions per methods

后端 未结 7 1991
栀梦
栀梦 2020-12-23 13:19

I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views.

Reading the documentation I se

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-23 14:06

    If you use ViewSets or ModelViewSets, I think overwriting get_permissions will do the trick.
    Take a look at how djoser handles this.

    Example:

    class UserViewSet(viewsets.ModelViewSet):
        permission_classes = settings.PERMISSIONS.user  # default
    
        def get_permissions(self):
            if self.action == "activation":  # per action
                self.permission_classes = settings.PERMISSIONS.activation
            return super().get_permissions()
    
        @action(["post"], detail=False)  # action
        def activation(self, request, *args, **kwargs):
            pass
    
        
    

提交回复
热议问题