Returning custom message when a permission is denied in DRF

前端 未结 7 1943
盖世英雄少女心
盖世英雄少女心 2021-02-13 01:20

Django REST Framework has an excellent piece of documentation about permissions. I\'ve been able to use pre-made permission classes and also built my own.

However, there

7条回答
  •  北海茫月
    2021-02-13 01:59

    when permission isn't granted, I will raise a exception which custom response. It works on djangorestframewor(3.10.1) and django(2.2.3).

    from rest_framework.permissions import BasePermission
    from rest_framework.exceptions import APIException
    from rest_framework import status
    
    
    class IsLogin(BasePermission):
        """
        Allows access only to authenticated users.
        """
    
        def has_permission(self, request, view):
            if request.email:
                return True
            raise NeedLogin()
    
    
    class NeedLogin(APIException):
        status_code = status.HTTP_403_FORBIDDEN
        default_detail = {'error': True, 'message': 'need login'}
        default_code = 'not_authenticated'
    

提交回复
热议问题