Django模型的clean方法多重错误 [英] Django model's clean method multiple error
本文介绍了Django模型的clean方法多重错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在玩我的测试项目
I have been playing around with my test project
我的模型中有这种干净的方法
I have this clean method in my model
class SomeModel(models.Model):
f1 = models.IntegerField()
f2 = models.IntegerField()
def clean(self):
if self.f1 > self.f2:
raise ValidationError({'f1': ['Should be greater than f1',]})
if self.f2 == 100:
raise ValidationError({'f2': ['That's too much',]})
我真的不知道如何引发这两个错误并将其显示在管理页面中,因为即使两个 if
为 True
,也只有第一个如果显示
错误(很明显),如何显示两个错误?
I don't really know how to raise both errors and show it in the admin page because even if the two if
is True
, only the first if
error is shown(obviously) how do I show both errors?
推荐答案
您可以构建错误的 dict
并在完成时引发ValidationError(如有必要):
You could build a dict
of errors and raise a ValidationError when you are done (if necessary):
class SomeModel(models.Model):
f1 = models.IntegerField()
f2 = models.IntegerField()
def clean(self):
error_dict = {}
if self.f1 > self.f2:
error_dict['f1'] = ValidationError("Should be greater than f1") # this should probably belong to f2 as well
if self.f2 == 100:
error_dict['f2'] = ValidationError("That's too much")
if error_dict:
raise ValidationError(error_dict)
这篇关于Django模型的clean方法多重错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文