简体   繁体   English

Django 模型的清理方法多次错误

[英]Django model's clean method multiple error

I have been playing around with my test project我一直在玩我的测试项目

I have this clean method in my model我的 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',]})

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?我真的不知道如何引发这两个错误并在管理页面中显示它,因为即使两个ifTrue ,只有第一个if显示错误(显然)我如何显示这两个错误?

You could build a dict of errors and raise a ValidationError when you are done (if necessary): 您可以构建一个错误dict并在完成后引发ValidationError(如有必要):

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)

I would expand the accepted answer by setting a classmethod like this:我会通过设置这样的类方法来扩展接受的答案:

@classmethod
def add_error(cls, errordict, error):
    for key, value in error.items():
        if key in errordict:
            if isinstance(errordict[key], str) or isinstance(errordict[key], ValidationError):
                errordict.update({key: [errordict[key], value]})
            elif isinstance(errordict[key], list):
                errordict[key].append(value)
        else:
            errordict.update(error)
    return errordict

That way, if a key already exists in your error dict, it will be casted in a list.这样,如果您的错误字典中已经存在一个键,它将被放入一个列表中。 That way, all the errors will be raised, even if there are multiple errors per field.这样,即使每个字段有多个错误,也会引发所有错误。

adderror(error_dict, {'field', 'error message'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM