How to override save method in admin ?

Django admin

April 2020

Sometimes after adding or editing model in the admin, it should be useful to do some custom code when saving the data.

You can find the source code in this repository

Such as setting a field or whatever else. To do so, just override the save_model method and write your custom code

    def save_model(self, request, obj, form, change):
        if request.user.is_superuser:
            pass
        else:
            #do your own custom code
            pass
        obj.save()

How to do some validations without implementing a custom form

If you want to do some validations and display an error message in the admin, you can also add a clean method in your models.py for the model to which you want to do some validations

class Product(models.Model):
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
    refShop = models.ForeignKey(Shop, db_index=True,on_delete=models.CASCADE)
    title = models.TextField(max_length=65)
    price = models.FloatField(default=0)
    withEndDate = models.BooleanField(default=False)
    endDate = models.DateField(blank=True,null=True)
    description = models.CharField(max_length=65, default='', null=True, blank=True)
    createdAt = models.DateTimeField(auto_now_add=True)
    updatedAt = models.DateTimeField(auto_now=True)
    available = models.BooleanField(default=True)

    def clean(self):
        from datetime import datetime, timedelta
        from django.core.exceptions import ValidationError

        today = datetime.now().date()
        if self.endDate:
            if self.endDate < today:
                raise ValidationError("You cannot set an endDate in the past")

        if self.withEndDate and self.endDate is None:
            raise ValidationError("Please select an end date !")

This clean method will check if the endDate entered by the user is not in the past.

Django admin custom validation

It will also check if an withEndDate is checked then the endDate field must be set.

Django admin check validation

Christophe Surbier