user2770624
user2770624

Reputation: 393

SlugField in Django and overriding save

I am writing an app and learning at the same time. I am about to implement the a SlugField in on of my models, in an example piece of code I found on Tango with Django the author overrode the save function. I am having a hard time understanding why they would do this.

Code from Tango with Django:

from django.template.defaultfilters import slugify

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
            self.slug = slugify(self.name)
            super(Category, self).save(*args, **kwargs)

    def __unicode__(self):
            return self.name

Upvotes: 2

Views: 3013

Answers (1)

Below the Radar
Below the Radar

Reputation: 7635

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.

Upvotes: 3

Related Questions