When building a web application, it is essential to create unique URLs for each page to ensure that they can be easily accessed and shared by users. In Django, this can be achieved by using a slug field to generate unique URLs for each item in a database. A slug is a URL-friendly version of a string that is used as a unique identifier for a resource.
In this tutorial, we will go over the steps to create a unique slug in Django.
1. Define the Slug Field
The first step is to add a slug field to the model you want to generate a unique slug for. To do this, add the following code to your model:
from django.db import models from django.utils.text import slugify class MyModel(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(MyModel, self).save(*args, **kwargs) def __str__(self): return self.title
In this code, we have added a slug
field to our MyModel
model. We have also added a save
method that generates a unique slug using the slugify
function from Django’s utils
module.
2. Add the Slug to the URL Pattern
The next step is to add the slug to the URL pattern for the model. To do this, add the following code to your urls.py
file:
from django.urls import path from .views import MyModelDetailView urlpatterns = [ path('<slug:slug>/', MyModelDetailView.as_view(), name='my_model_detail'), ]
In this code, we have added a path to the MyModelDetailView
class, which takes a slug
parameter as part of the URL. This ensures that each item in the database has a unique URL based on its slug.
3. Create the Detail View
The final step is to create the detail view for the model. To do this, add the following code to your views.py file:
from django.shortcuts import render from django.views.generic import DetailView from .models import MyModel class MyModelDetailView(DetailView): model = MyModel template_name = 'my_model_detail.html' context_object_name = 'my_model'
In this code, we have created a MyModelDetailView
class that inherits from Django’s DetailView
class. We have also specified the model, template, and context object name for the view.
4. Test the Unique Slug
Now that we have added a slug field to our model, added it to the URL pattern, and created a detail view, we can test that the slug is generating a unique URL for each item in the database.
To test this, create some instances of MyModel
in the Django admin panel, and give them unique titles. Then, navigate to the detail view for each item and verify that the URL includes the unique slug for that item.

Conclusion
In this tutorial, we have gone over the steps to create a unique slug in Django. By adding a slug
field to our model, adding it to the URL pattern, and creating a detail view, we can generate unique URLs for each item in the database. This makes it easier for users to access and share individual resources within our web application.