Auto generating unique slug in Django

In this post we are going to know how to generate unique slug in django automatically. So what is slug? Consider the URL of this post: /auto-generating-unique-slug-in-django/ . Here the bold part of the URL is called slug.

First, consider a model Article in which we will generate the unique slug.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django.db import models


class Article(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(max_length=140, unique=True)
    content = models.TextField()

    def __str__(self):
        return self.title

In our model Article we have three fields: title, slug and content. Django provides a built-in model field for slug, SlugField. We will generate the slug based on the title field.

How the slug will be generated: If the title of our first article is ‘New article’, the slug will be ’new-article’. If the title of our second article is also ‘New article’, the slug will be ’new-article-1’.  And if the title of our third article is ‘New article’ again, the slug will be ’new-article-2’. And so on.

So, to do that we have to write code like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.db import models
from django.utils.text import slugify


class Article(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(max_length=140, unique=True)
    content = models.TextField()

    def __str__(self):
        return self.title

    def _get_unique_slug(self):
        slug = slugify(self.title)
        unique_slug = slug
        num = 1
        while Article.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

Look at the line 22, we override the save() method here. If the slug doesn’t already exist in the instance of Article, we generate it by calling _get_unique_slug() method. I am not explaining the code of _get_unique_slug() method in detail because it is kind of self explanatory. But what slugify() does? Well, if we give a string like ‘The new article title’ to slugify(), it returns ’the-new-article-title’. Simple.

You can also consider to use the pre_save signal instead of overriding the save method.

Thanks for reading this post. Have a nice day!

You should consider to read this post as well: Auto generating unique slug in Django: a generic approach.

Load Comments?