使用Django Rest Framework的自定义验证错误消息

时间:2017-06-26 10:16:58

标签: django django-rest-framework

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
}

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以在提供响应序列化器时根据视图中的表格更改错误。错误可以代替,您可以将自己的字典传递给该错误

答案 2 :(得分:-1)

您可以覆盖序列化程序validate()方法并引发自定义验证

def validate(self, data):
    #validations here..
    response = {
                    "message": "customer with this phone already 
                                exists, customer with this 
                                email already exists, customer with
                                this tenant id already exists"
                    "success": false,
                    "error": 1
                }
    try:
        Customer.objects.get(phone=data['phone'], email=data['email'],
                             tenant_id=data['tenant_id'])
        raise serializers.ValidationError(response["message"])
        #or you could return a json response.
        #return Response(response)
    except:
        return data