Add a Slugfield & Overwrite Save in Django Model

To add a SlugField and overwrite the save method in a Django model, follow these steps:

  1. Define the SlugField in the Model: Add a SlugField to your model to store the slug.
  2. Overwrite the Save Method: Customize the save method to automatically generate and assign a slug value before saving the object.

Here’s a step-by-step example:

Step 1: Install Django Extensions (Optional)

If you want to use the slugify function from Django Extensions, install it via pip:

pip install django-extensions

Step 2: Modify Your Model

from django.db import models
from django.utils.text import slugify

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            # Generate a unique slug
            self.slug = slugify(self.name)
            # Ensure the slug is unique
            unique_slug = self.slug
            num = 1
            while MyModel.objects.filter(slug=unique_slug).exists():
                unique_slug = f'{self.slug}-{num}'
                num += 1
            self.slug = unique_slug
        super(MyModel, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

Explanation:

  1. SlugField Definition:
    slug = models.SlugField(unique=True, blank=True)
    
    • unique=True ensures that each slug is unique.
    • blank=True allows the field to be empty in the form (the slug will be generated automatically if not provided).
  2. Overwriting the Save Method:
    • The save method is overridden to generate a slug if it doesn’t exist.
    • slugify(self.name) generates a slug from the name field.
    • A while loop ensures the slug is unique by appending a number if a conflict is found.
    • The super(MyModel, self).save(*args, **kwargs) call saves the model instance.

Optional: Using Django Extensions (if installed)

If you installed Django Extensions, you can use its slugify function instead of the one from Django’s utilities:

from django_extensions.db.fields import AutoSlugField

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    slug = AutoSlugField(populate_from='name', unique=True)

    def __str__(self):
        return self.name

This approach simplifies the slug generation and ensures uniqueness using the AutoSlugField.

With these steps, you can add a SlugField and overwrite the save method in your Django model to automatically generate and ensure unique slugs for your model instances.