Categories
Python Answers

How to raise a validation error in a model’s save method in Python Django?

Spread the love

Sometimes, we want to raise a validation error in a model’s save method in Python Django.

In this article, we’ll look at how to raise a validation error in a model’s save method in Python Django.

How to raise a validation error in a model’s save method in Python Django?

To raise a validation error in a model’s save method in Python Django, we can use is_clean to check if the model is cleaned.

For instance, we write

class BaseModelExt(models.Model):
    is_cleaned = False

    def clean(self):
        # ...
        self.is_cleaned = True

    def save(self, *args, **kwargs):
        if not self.is_cleaned:
            self.clean()

        super().save(*args, **kwargs)

to add the clean method into our model class.

After the validation checks are run in clean, we set self.is_cleaned to True.

And then in save, we call clean is is_cleaned is False.

Finally, we call save to save the values.

Conclusion

To raise a validation error in a model’s save method in Python Django, we can use is_clean to check if the model is cleaned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *