[Django]-SlugField in Django and overriding save

3👍

The use of overiding the save method is to perform some actions each time an instance of the model is saved.

In your example, everytime an instance of your model is saved, the save method will transform the name value into a slug value with the function slugify() and save it into the slug field.

It’s a way to automatically transform the name value into a slug and then saving it in the slug field.

def save(self, *args, **kwargs):
        #this line below give to the instance slug field a slug name
        self.slug = slugify(self.name)
        #this line below save every fields of the model instance
        super(Category, self).save(*args, **kwargs) 

For instance, in a form for this model, you wont have to include an input for the slug field, the save method will populate it based on the value of the name input.

Leave a comment