如何正确捕获和嵌套ValidationErrors

时间:2018-08-08 19:30:59

标签: django

我想嵌套验证错误,以便查明错误的确切原因,但是看来Django的ValidationError不允许嵌套嵌套错误。

这是一个玩具示例:

def not_nested():
        raise ValidationError(_('invalid'))

def nested():
    errors = dict()
    for x in ['a', 'b', 'c']:
        try:
            not_nested()
        except ValidationError as e:
            errors[x] = e
    if errors:
        raise ValidationError(errors)

def nested_again():
    errors = dict()
    for x in ['1', '2', '3']:
        try:
            nested()
        except ValidationError as e:
            errors[x] = e
    if errors:
        raise ValidationError(errors)

单层嵌套效果很好

nested()
# raises:
ValidationError: {'a': ['invalid'], 'b': ['invalid'], 'c': ['invalid']}

但是嵌套两次不会:

nested_again()
# raises
AttributeError: 'ValidationError' object has no attribute 'error_list'

这是故意的还是错误?还有另一种方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您可以从error_dict对象访问ValidationError

def nested_again():
    errors = dict()
    for x in ['1', '2', '3']:
        try:
            nested()
        except ValidationError as e:
            errors[x] = e.error_dict  # Here
    if errors:
        raise ValidationError(errors)