Last modified: Dec 03, 2026

Django SlugField Examples for Beginners

A SlugField is one of the most useful fields in Django. It stores short, URL-friendly text. You often see slugs in blog post URLs like /my-first-post/.

This guide walks you through Django SlugField with simple, practical examples. You will learn how to add it, validate it, and use it in real projects.

What Is a Slug?

A slug is a short label for something. It contains only letters, numbers, underscores, or hyphens. It is safe to use inside a URL.

For example, the title "Hello World Post!" becomes the slug hello-world-post. Spaces turn into hyphens. Special characters are removed.

Django gives you a built-in field for this job. It handles storage and validation for you.

Basic SlugField Example

Let's start with a simple model. Import models and add a SlugField to your class.


from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    # SlugField stores URL-friendly text
    slug = models.SlugField(max_length=200)

    def __str__(self):
        return self.title

This model stores a title and a slug. The slug is limited to 200 characters. That matches the title length here.

If you are new to models and classes, start with Python class basics for beginners to understand how these structures work.

Useful SlugField Options

The SlugField accepts several arguments. Each one changes how your data behaves.

The unique argument prevents duplicate slugs. This is important for URLs. Two pages cannot share the same address.


class Post(models.Model):
    title = models.CharField(max_length=200)
    # unique=True blocks duplicate slugs
    slug = models.SlugField(max_length=200, unique=True)

The db_index argument adds a database index. Lookups by slug become faster. This helps when your table grows large.


class Post(models.Model):
    title = models.CharField(max_length=200)
    # db_index=True speeds up lookups
    slug = models.SlugField(max_length=200, db_index=True)

The allow_unicode argument lets slugs contain non-ASCII characters. This is useful for multilingual sites.


class Post(models.Model):
    title = models.CharField(max_length=200)
    # allow_unicode=True supports non-English slugs
    slug = models.SlugField(max_length=200, allow_unicode=True)

SlugField in the Admin

By default, the admin form shows a plain text input. You can prefill the slug from the title. This saves typing and avoids mistakes.

Use the prepopulated_fields option in your admin class. It fills the slug as you type the title.


from django.contrib import admin
from .models import Post

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    # Auto-fill slug from the title field
    prepopulated_fields = {"slug": ("title",)}

Now the admin generates the slug automatically. You can still edit it by hand if needed.

Creating Slugs with slugify

Django ships with a helper called slugify. It converts any text into a valid slug. This is handy when you save data outside the admin.


from django.utils.text import slugify

print(slugify("My First Django Post!"))

my-first-django-post

You can call it inside the save method. This ensures every post gets a slug, even when created by code.


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

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank=True)

    def save(self, *args, **kwargs):
        # Build the slug only if it is empty
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

This pattern keeps your URLs clean. It also protects against empty slugs.

Using SlugField in URLs

Slugs are made for URLs. You can capture them with a path converter. Django has a built-in slug converter.


from django.urls import path
from . import views

urlpatterns = [
    #  matches valid slug text
    path("post//", views.post_detail, name="post_detail"),
]

Your view then looks up the object by slug. Use get_object_or_404 to handle missing pages safely.


from django.shortcuts import get_object_or_404, render
from .models import Post

def post_detail(request, slug):
    # Fetch the post or return a 404 page
    post = get_object_or_404(Post, slug=slug)
    return render(request, "post_detail.html", {"post": post})

The result is a clean, readable URL such as /post/my-first-django-post/.

SlugField Validation Rules

The field checks its input with a validator. Only letters, numbers, underscores, and hyphens are allowed. Spaces and symbols fail validation.

You can also use the full_clean method to validate a model instance manually. It raises an error when the slug is invalid.


post = Post(title="Bad Slug", slug="bad slug!")
try:
    # full_clean runs all field validators
    post.full_clean()
except Exception as e:
    print(e)

{'slug': ['Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.']}

This is why generating slugs with slugify is a good habit. It removes invalid characters for you.

Handling Duplicate Slugs

With unique=True, a duplicate slug raises an error. Two posts with the same title would clash. A common fix is to add a number suffix.


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

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True, blank=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            base = slugify(self.title)
            slug = base
            counter = 1
            # Add a number until the slug is free
            while Post.objects.filter(slug=slug).exists():
                slug = f"{base}-{counter}"
                counter += 1
            self.slug = slug
        super().save(*args, **kwargs)

Now titles like "Hello World" and "Hello World!" get different slugs. The second one becomes hello-world-1.

SlugField vs CharField

A CharField stores any text. A SlugField stores text with strict rules. It is a CharField with a built-in slug validator.

Use SlugField when the value goes into a URL. Use CharField for free text like names or descriptions.

Understanding how fields and methods attach to classes helps here. Review Python class methods and attributes to see how model methods like save work.

Common Mistakes to Avoid

Do not forget unique=True on slugs used in URLs. Duplicates break routing and confuse users.

Do not build slugs by hand with string replace. Use slugify instead. It handles edge cases correctly.

Also keep slug length within your field limit. A slug longer than max_length causes a database error.

If you override methods in your models, make sure you understand the parent class. Read inheritance in Python explained to learn how super works.

SlugField and Inheritance

Models are Python classes. You can reuse a slug field through inheritance. A base model with a slug saves repetition.


from django.db import models

class SlugBase(models.Model):
    # Shared slug field for child models
    slug = models.SlugField(max_length=200, unique=True)

    class Meta:
        abstract = True

class Post(SlugBase):
    title = models.CharField(max_length=200)

This is the same idea as single inheritance in Python example shows with plain classes. The child gets the parent's field for free.

For a wider view of class patterns, see types of Python inheritance. Django models follow the same rules.

Conclusion

Django SlugField makes clean, readable URLs easy. It validates input and fits naturally into models, admin, and routes.

Start with a basic field. Add unique=True and db_index=True for URLs. Generate values with slugify and handle duplicates with a counter.

Follow these examples and your Django URLs will stay short, safe, and SEO-friendly.