【问题标题】:Custom Validation Error Message using Django Rest Framework使用 Django Rest 框架的自定义验证错误消息
【发布时间】:2017-11-29 03:53:37
【问题描述】:

DRF 给出的默认验证错误消息是密钥和消息的列表。将此格式自定义为文本格式的最佳方法是什么。例如。

这是默认格式。

{
"message": {
    "phone": [
        "customer with this phone already exists."
    ],
    "email": [
        "customer with this email already exists."
    ],
    "tenant_id": [
        "customer with this tenant id already exists."
    ]
},
"success": false,
"error": 1
}

这是我想要的。

{
"message": "customer with this phone already exists, customer with this 
email already exists, customer with this tenant id already exists"
"success": false,
"error": 1
}

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    通常的做法是显示单个字段的验证消息,而不是提供单个常规消息。所以 DRF 的默认行为是遵循这个约定。

    要实现您想要的,您需要为您的序列化程序 http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation 创建对象级验证,并防止字段验证的默认行为。

    【讨论】:

      【解决方案2】:

      您可以根据您在视图中的表单更改您的错误,此时您将给出响应 serializer.errors 而不是您可以将自己的字典传递给那个

      【讨论】:

      • 来自评论:您能改进您的解决方案的描述吗?能否提供一些示例源代码?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 2016-04-18
      相关资源
      最近更新 更多