DRF:自定义权限被拒绝消息 [英] DRF : Custom permission denied message

查看:26
本文介绍了DRF:自定义权限被拒绝消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将默认的拒绝DRF-权限消息
{"detail":"You do not have permission to perform this action."}更改为如下所示:
{"status": False, "message": "You do not have permission to perform this action."}

我找到了此SO Answer,但将Key更改为message

无济于事

推荐答案

若要将状态包括到错误响应中,您可以编写自定义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'
}

这篇关于DRF:自定义权限被拒绝消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆