Py学习  »  Django

如何从django内置的唯一字段验证erro响应中删除第三个括号“[]”

Sreebash Chandra Das • 2 年前 • 539 次点击  

这是我的模型

在这个CustomerAdd表中,我用Django builtins unique=True设计了customer_手机。对于这些独特的领域,Django提出 验证错误如下: { “客户电话”:[ “此客户电话已注册。” ] } 如何从内置验证错误中删除第三方括号!请帮帮我。

class CustomerAdd(models.Model):
    user = models.ForeignKey('accounts.CustomUser', on_delete=models.CASCADE)
    is_customer = models.BooleanField('customer status', default=True)
    is_supplier = models.BooleanField('supplier status', default=False)
    customer_name = models.CharField(max_length=100)
    customer_phone = models.CharField(max_length=15, unique=True, error_messages={'unique': "This customer_phone has "
                                                                                            "already been registered."})
    previous_due = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    date = models.DateField(auto_now_add=True)
    picture = models.ImageField(upload_to='customer_add_pics', default='images.png')

    def __str__(self):
        return self.customer_name

    class Meta:
        verbose_name = "Customer Add"
        verbose_name_plural = "Customer Add"

以下是API的回应:

{
    "customer_phone": [
        "This customer_phone has already been registered."
    ]
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129033
 
539 次点击  
文章 [ 1 ]  |  最新文章 2 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    2 年前

Django引发了以下验证错误: { "customer_phone": [ "This customer_phone has already been registered." ] }

发生这种情况的原因是,同一个字段可以 倍数 错误。例如,密码字段可以要求至少包含八个字符,并且至少包含一个数字。通过使用列表,它可以列出一个 或者更多 同一领域的问题。从建模的角度来看,这是一种报告错误的更合理的方法。

你可以实现 custom exception handling  [drf-doc] 要对每个字段仅使用第一项,请执行以下操作:

# app_name/utils.py

from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError

def custom_exception_handler(exc, context):
    if isinstance(exc, ValidationError) and isinstance(exc.detail, dict):
        data = {
            k: vs[0]
            for k, vs in exc.detail.items()
        }
        exc = ValidationError(detail=data)
    
    return exception_handler(exc, context)

然后将异常处理程序设置为:

# settings.py

REST_FRAMEWORK = {
    # …,
    'EXCEPTION_HANDLER': 'app_name.utils.custom_exception_handler'
}

但我认为这是 好主意。一个字段可能会有多个问题,从而引发多个验证错误。