Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model's clean method multiple error

Tags:

python

django

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',]})

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?

like image 845
Juan Carlos Asuncion Avatar asked Jun 07 '26 01:06

Juan Carlos Asuncion


1 Answers

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)
like image 190
user2390182 Avatar answered Jun 10 '26 03:06

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!