【问题标题】:Validation codes and messages in Django Rest FrameworkDjango Rest Framework 中的验证代码和消息
【发布时间】:2015-01-26 17:49:13
【问题描述】:

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

{
    "product": [
        "This field must be unique."
    ],
    "price": [
        "This field is required."
    ]
}

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

{
    "product": [
        {
          "code": "unique",
          "message": "This field must be unique."
        }
    ],
    "price": [
        { 
          "code": "required",
          "message": "This field is required."
        }
    ]
}

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

【问题讨论】:

标签: django validation django-rest-framework


【解决方案1】:

这个问题是很久以前发布的,所以我将在此处添加更新的答案。较新版本的 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)

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

REST_FRAMEWORK['EXCEPTION_HANDLER'] = 'my_module.full_details_exception_handler'

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

【讨论】:

    【解决方案2】:

    在你的序列化器中添加这样的东西:

    def is_valid(self, raise_exception=False):
        try:
            return super(ClientSerializer, self).is_valid(raise_exception)
        except exceptions.ValidationError as e:
            if 'email' in e.detail:
                for i in range(len(e.detail['email'])):
                    if e.detail['email'][i] == UniqueValidator.message:
                        e.detail['email'][i] = {'code': 'not-unique'}
            raise e
    

    【讨论】:

    • 我想我正在寻找更通用的东西。这需要对每个字段和每个验证错误进行自定义,对吧?
    • 是的。而且很丑。问题#2878 修复后将消除所有丑陋。
    猜你喜欢
    • 2020-08-09
    • 1970-01-01
    • 2021-09-09
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2021-05-16
    • 2015-12-10
    相关资源
    最近更新 更多