How to Override Save Method in Django?

Published On: 09/12/2022 | Category: Django


Hi Dev,

Here, I will show you how to override save method in django. you'll learn override save method in django model. we will help you to give example of django model save override example. I’m going to show you about django override form save method.

The save method is an inherited model method that is used to save an instance into a specific Model. When attempting to create an instance of a model from the admin interface or the django shell, the save() function is invoked. Before storing the data in the database, we can override the save function to apply some constraints or fill some ready-only fields like SlugField.

Technically, overriding the save method to implement such functionalities is not advised because any error in the save method can cause the entire database to crash. Therefore, either try writing save methods and error handling to the best of your ability, or avoid doing so and try implementing these functionalities in forms, views, models, etc.

Here i explained simply step by step example of how to override save method in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core

Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'core',
]

Step 4: Update models.py File

For all field possibilities, we will be experimenting with CharField. In order to automatically fill the SlugField, we will override the save method.

core/models.py
from django.db import models

# importing slugify from django
from django.utils.text import slugify

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length = 200)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Article, self).save(*args, **kwargs)

I explain save method We utilise the super keyword because the save() method from its parent class has to be overridden. The function slugify turns any string into a slug. so we are converting the title to form a slug basically

Step 5: Prevent object from saving

Using the return statement, you can stop an instance from saving in the save() method.

def save(self, *args, **kwargs):
   if self.title == “i love coding”:
       return  # instance not save
   self.slug = slugify(self.title)
   super(Article, self).save(*args, **kwargs)

Step 6: Check if a new instance is created or updated

def save(self, *args, **kwargs):
    if self.id:
        print('updating')
    else:
        print('creating')
    super(Article, self).save(*args, **kwargs)

I hope it will help you....

Happy Coding!