我想嵌套验证错误,以便查明错误的确切原因,但是看来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'
这是故意的还是错误?还有另一种方法可以做到这一点吗?
答案 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)