Generate a slug in a Django Web Application
Sunntig,05 Septämber, 2021

One of the most tedious aspects of writing a blog post is writing the slug. For these not in the know a slug is simply the url at which your article will be reacheable: so if you have a post with a title “Hello World” the slug would be yourdomain.com/hello-world.

I have around web development for a while so I do remember the time where slugs were not really popular. Back in the early days of the Internet you would simply see IDs like myblog.com/?article=123456. At some point search engines started to give more weight to more visually friendly and readable URLs and by then all the major blogs or online journals used a slug.

Django 3 offers now a slug field but you can also auto generate a slug if you used models.CharField for your slug.

Here is how, first your import slugify

 from django.utils.text import slugify

then you modify your model as follow:

slug = models.CharField(max_length=155, null=True, blank=True)

and finally define a function to populate your slug field based on the title field (so if your title has spaces it will add the necessary - ) This example assume that your class is called Post:

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

This is all. Now adding a post in django admin will automatically add the slug based on the title.