Explain Codes LogoExplain Codes Logo

How do I create a slug in Django?

python
django
slug
models
Anton ShumikhinbyAnton Shumikhin·Feb 12, 2025
TLDR
from django.utils.text import slugify slug = slugify("Sample Article Title!") print(slug) # "sample-article-title" # Who doesn't love a cleanly done slug job?

This built-in function eliminates special characters and spaces, converts the text to lowercase, and uses hyphens to separate words, yielding a clean, web-friendly slug.

Implementing SlugField in Models

Generating Unique Slugs

Ensure your slugs are unique because a duplicate slug is as good as naming your twins with the exact same name, leading to a whole lot of chaos!

To keep slugs unique, use unique=True when defining your slug field in your model:

from django.db import models from django.utils.text import slugify # everyone's favorite slug-buster class Article(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) # Unique, like everyone on their first date def save(self, *args, **kwargs): if not self.id: # The ugly duckling who hasn't yet turned into a beautiful slug self.slug = slugify(self.title) super().save(*args, **kwargs) # Even Superman calls his dad

With if not self.id, the slug is created only when the object originates, ensuring link integrity even with subsequent edits.

Handling Unicode Characters

When non-ASCII characters baffle slugify, it's time for unidecode to join the slug-busting team:

from unidecode import unidecode from django.utils.text import slugify # Keep calm and slugify class Article(models.Model): # ... def save(self, *args, **kwargs): if not self.id: # Still waiting for the transformation ceremony self.slug = slugify(unidecode(self.title)) # Even Dracula turns into a slug! super().save(*args, **kwargs) # Dad answers the phone again

This combo transforms non-ASCII characters into their closest ASCII counterparts resulting in more accurate, readable slugs.

Automating Slug Generation in Django Admin

Who says admins don't need a break? Automate slug generation in Django admin using prepopulated_fields:

class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Article, ArticleAdmin) # The winner takes it all

This creates and updates the slug in tandem with your typing, keeping the slug in pace with the title.

Checklist for Advanced Scenarios

Customize Slug Generation

To stamp out uniqueness in each slug, add an iterative check to generate a new slug if a duplicate slug is detected:

def generate_unique_slug(klass, field): # Habitual slug generator origin_slug = slugify(field) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): # Deja vu? Not today! unique_slug = f'{origin_slug}-{numb}' numb += 1 return unique_slug class Article(models.Model): #... def save(self, *args, **kwargs): if not self.id: self.slug = generate_unique_slug(Article, self.title) # Slug treated like royalty super().save(*args, **kwargs)

Here, if the slug is similar to an existing slug, a number is appended thus ensuring uniqueness.

Prioritize SEO

In the world of SEO, your slug can be your secret weapon:

  • Keep slugs short, but descriptive. Short good. Long bad. SEO happy.
  • SEO loves keywords. Make slug happy with keywords.
  • Never change a slug once created. Broken links and SEO ranking drop! Nightmare?

Streamline Save in the Model

class Article(models.Model): # ... def save(self, *args, **kwargs): if not self.id and not self.slug: self.slug = slugify(self.title) # Old habits die hard super().save(*args, **kwargs)

Potential redundant slug creation is averted by ensuring the save method doesn't summon slugify multiple times before the object is saved to the database.