[Django]-How to call my field validators in my save method in Django?

5👍

Here’s the validating objects documentation. Basically, if you call an object’s full_clean() method, you’ll run all validations on the object. You can run only the individual field validators by calling self.clean_fields().

But in general, it’s not good practice to add validation in the save() method. The reason is that in most Django apps, you’d create a form (a ModelForm) which would call the validation methods and be able to return something meaningful to the user when validation fails.

When the model’s save() method is called it’s too late to show something to the user, so you can only raise an exception at that point (and crash).

The normal procedure (which the admin forms use) is: validate the form by calling form.is_valid() (which calls full_clean() on the model), then if and only if the form is valid, save the model.

The shell is not the regular interaction method and should be used only very carefully as it bypasses the normal flow of the application.

Leave a comment