Django Rest Framework custom permissions per view

前端 未结 3 2010
-上瘾入骨i
-上瘾入骨i 2021-02-10 00:36

I want to create permissions in Django Rest Framework, based on view + method + user permissions.

Is there a way to achieve this without manually writing each permission

3条回答
  •  失恋的感觉
    2021-02-10 01:35

    Custom permission can be created in this way, more info in official documentation( https://www.django-rest-framework.org/api-guide/permissions/):

    from rest_framework.permissions import BasePermission
    
    
    # Custom permission for users with "is_active" = True.
    class IsActive(BasePermission):
        """
        Allows access only to "is_active" users.
        """
        def has_permission(self, request, view):
            return request.user and request.user.is_active
    
    # Usage
    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    from .permissions import IsActive   # Path to our custom permission
    
    class ExampleView(APIView):
        permission_classes = (IsActive,)
    
        def get(self, request, format=None):
            content = {
                'status': 'request was permitted'
            }
            return Response(content)
    

提交回复
热议问题