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

时间:2018-02-15 12:57:04

标签: django django-rest-framework django-permissions

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

我找到了此SO Answer,但无法更改Key的{​​{1}}

2 个答案:

答案 0 :(得分:3)

您可以通过扩展BasePermission类来创建自定义权限,并使用自定义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

答案 1 :(得分:3)

要在错误响应中包含状态,您可以编写自定义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'
}
相关问题