Django Rest Framework中的验证代码和消息

Jus*_*ris 7 django validation django-rest-framework

使用序列化程序中的开箱即用字段,验证错误消息如下所示:

{
    "product": [
        "This field must be unique."
    ],
    "price": [
        "This field is required."
    ]
}
Run Code Online (Sandbox Code Playgroud)

但是,对于我正在编写的API,我想为每个失败的验证提供唯一的错误代码,以便客户端可以以编程方式响应验证错误,或者可以在UI中提供自己的自定义消息.理想情况下,错误json看起来像这样:

{
    "product": [
        {
          "code": "unique",
          "message": "This field must be unique."
        }
    ],
    "price": [
        { 
          "code": "required",
          "message": "This field is required."
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

使用ValidationErrors的当前方法使得这相当困难.查看代码,似乎目前不支持此类错误报告.但是,我正在寻找一种方法来覆盖错误处理以适应此模型.

Jus*_*ris 5

这个问题已经发布很久了,所以我将在此处添加更新的答案。较新版本的DRF现在支持此功能,但仍需要一些自定义代码。使用以下技巧创建一个新的异常处理程序:

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException


def full_details_exception_handler(exc, context):
    """
    This overrides the default exception handler to
    include the human-readable message AND the error code
    so that clients can respond programmatically.
    """
    if isinstance(exc, APIException):
        exc.detail = exc.get_full_details()

    return exception_handler(exc, context)
Run Code Online (Sandbox Code Playgroud)

然后将DRF配置为在您的设置中使用该自定义处理程序:

REST_FRAMEWORK['EXCEPTION_HANDLER'] = 'my_module.full_details_exception_handler'
Run Code Online (Sandbox Code Playgroud)

如果可以在DRF本身中将此配置添加为配置选项,那就太好了,但这是一个包含错误代码的轻量级解决方案。