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

芝麻糊 阅读:69 2025-06-02 22:19:02 评论:0

如何将默认的 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."}我找到了这个SO Answer,但无助于更改Keymessage

请您参考如下方法:

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


标签:Django
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号