🔗 Django Add Slug Field – Create SEO-Friendly URLs in Your Models (2025 Guide)
🧲 Introduction – What Is a Slug in Django?
A slug is a short, URL-friendly version of a string—commonly used for blog titles, product names, or category pages. In Django, you can add a SlugField to your model to create clean, readable, and SEO-optimized URLs like:
https://example.com/blog/django-template-syntax/
🎯 In this guide, you’ll learn:
- How to add a
SlugFieldto your model - How to auto-generate slugs from titles
- How to use slugs in URLs and views
- Best practices for uniqueness and SEO
🧱 Step 1: Add a Slug Field to Your Model
models.py
from django.db import models
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
slug = models.SlugField(unique=True, blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def __str__(self):
return self.title
✅ slugify() automatically converts “My First Post” ➝ my-first-post.
🔄 Step 2: Make Migrations
python manage.py makemigrations
python manage.py migrate
🌐 Step 3: Use the Slug in URLs
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('post/<slug:slug>/', views.post_detail, name='post-detail'),
]
🧩 Step 4: Update the View to Use Slug
views.py
from django.shortcuts import get_object_or_404, render
from .models import Post
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog/post_detail.html', {'post': post})
✅ Now, posts can be accessed via their slug:
/post/django-template-tags/
🖥️ Optional: Display Slug in Admin (Read-Only)
admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
list_display = ("title", "slug")
admin.site.register(Post, PostAdmin)
✅ Best Practices
- ✅ Set
unique=Trueto prevent slug conflicts - ✅ Use
slugify()to auto-generate slugs safely - ✅ Always check if the slug already exists before saving
- ✅ Use slugs for readability and SEO benefit
📌 Summary – Recap & Next Steps
🔍 Key Takeaways:
- Slugs make URLs clean, readable, and SEO-friendly
- Use
SlugFieldwithslugify()for auto-generation - Use slugs in your URL patterns and views instead of IDs
- Update your admin and detail pages to support slugs
⚙️ Real-World Relevance:
Slugs are critical for blogs, news sites, product pages, and SEO-focused websites—offering both user-friendly and search engine-friendly links.
❓ Frequently Asked Questions (FAQ)
❓ What if two posts have the same title?
✅ Use a custom function to append a number or timestamp if the slug exists:
from django.utils.text import slugify
def unique_slug(instance, title):
base_slug = slugify(title)
slug = base_slug
num = 1
while Post.objects.filter(slug=slug).exists():
slug = f"{base_slug}-{num}"
num += 1
return slug
❓ Can I manually set the slug?
✅ Yes. Just fill it in the admin or form. If blank, it auto-generates.
❓ Can I use slugs with other models?
✅ Yes. Slugs work with any model—categories, authors, tags, etc.
❓ Is the slug field case-sensitive?
🚫 No. It’s treated as case-insensitive in most database backends.
❓ Should I make the slug field editable?
🟡 Only if you want manual control. Otherwise, keep editable=False.
Share Now :
