DRF:自定义权限被拒绝消息

DRF : Custom permission denied message

如何将默认的 DRF-Permission Denied 消息
{"detail":"You do not have permission to perform this action."} 更改为类似这样的内容,
{"status": False, "message": "You do not have permission to perform this action."}

我找到了这个 ,但它无助于为 message

更改 Key

您可以通过扩展 BasePermission class 创建自定义权限,并使用自定义 status_codedefault_detail 的自定义异常以在该自定义权限中使用。

class CustomForbidden(APIException):
    status_code = status.HTTP_403_FORBIDDEN
    default_detail = "custom error message"


class CustomPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if not_allowed:
            raise CustomForbidden

要在错误响应中包含状态,您可以编写自定义 error handler:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response.status_code == 403:
        response.data = {'status': False, 'message': response.data['detail']}

    return response

在设置中:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 
'my_project.my_app.utils.custom_exception_handler'
}