Working With Slugs In Django

My approach to efficiently working with slugs, creating slugs at the proper stage, and using slugs for seo.

Introduction

Slugs are used to identify a particular in a human-readable, and URL friendly way. For example, "an-article-about-slugs." Slugs are useful in allowing both the person and machine to understand what resource a URL points to. Additionally, a well-constructed slug contributes to search engine optimization (SEO). While a resource could be identified by a numerical key alone, you generally stand to benefit by using slugs.

Here's my approach.

Set up

For demonstration purposes, I'll use the following model:

from django.db import models


class Article(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    published_at = models.DateTimeField(blank=True, null=True)
    ...
    slug = models.SlugField(blank=True, null=True)

The slug field should be allowed to be blank when you create the object. This allows for the article to evolve in its draft phase without having to commit to a specific slug. I enforce the slug being present when the article is published.

Creating Slugs

Django provides a function for converting a strings to slugs: slugify. I use this utility to create the slug based on the title if the user already hasn't input the slug manually. I like to nest this logic in the model's "clean()" method. This method isn't called by default, so we'll need to override the model's "save()" method and add a call to "full_clean()" which then calls "clean()."

from django.utils.text import slugify


class Article(models.Model):
    ...

    def save(self, *args, **kwargs):
        self.full_clean()  # the full_clean() method will call clean()
        super().save(*args, **kwargs)

    def clean(self):
        if self.published_at and not self.slug:
            # we have an article that is being published but a slug has not been provided by the user
            # so let's create one using the Django slugify function
            self.slug = slugify(self.title)

Using Slugs

Now that we've established a method for creating slugs for our articles, let's integrate slugs into our URL patterns and views. For example:

# views.py

from django.views.generic import DetailView
from models import Article


class ArticleDetailViews(DetailView):
    model = Article
    pk_url_slug = "article"


# urls.py

from django.urls import path
from views import ArticleDetailView


urlpatterns = [
    path("article/<slug:article>/", ArticleDetailView.as_view(), name="article-detail"),
]

Using the slug example in the introduction section ("an-article-about-slugs"), the full URL based on the above pattern will be: "article/an-article-about-slugs/."

Final Thoughts

Slugs are an important component to any content platform that fetches resources dynamically through a URL. Be careful when creating slugs and try to avoid situations where they need to be changed. SEO can suffer when modifying slugs for published articles. Automate as much as you can, like we did with the above function "slugify." Follow these steps in conjunction with other best practices, and you'll be on your way to using slugs to in your own project.

Details
Published
September 3, 2023
Topics
Tags
Next
August 27, 2023

Next Article Suggestion in Django

Considerations in developing a content suggestion engine in Django.