When building a web application with Django, creating clean and descriptive URLs is just as important as writing good content. This is where Django’s SlugField comes in handy. Instead of confusing numbers in your URL, slugs make them more readable and SEO-friendly.
What is a Slug in Django?
A slug is the part of a URL that contains a readable identifier, often made up of letters, numbers, hyphens, or underscores.
For example:
- URL without slug:
127.0.0.1:8000/members/details/1
- URL with slug:
127.0.0.1:8000/members/details/emil-refsnes
The second option is easier to read, share, and optimize for search engines.
Why Should You Use Slugs?
Using slugs instead of database IDs improves both user experience and SEO. For developers, IDs might make sense, but visitors appreciate clear, descriptive links.
Benefits of Slugs:
- URLs look professional and trustworthy
- Better search engine optimization (keywords in slugs help rankings)
- Easier for users to remember and share
Step 1: Add a SlugField in models.py
Start by adding the slug
field to your Django model. Open your models.py
file and include a SlugField:
pythonfrom django.db import models
class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
slug = models.SlugField(default="", null=False)
def __str__(self):
return f"{self.firstname} {self.lastname}"
Now, you need to update the database:
bashpython manage.py makemigrations
python manage.py migrate
Step 2: Update the Admin Panel
We want Django to generate slugs automatically instead of typing them manually each time. To do this, modify your admin.py
.
pythonfrom django.contrib import admin
from .models import Member
class MemberAdmin(admin.ModelAdmin):
list_display = ("firstname", "lastname", "joined_date",)
prepopulated_fields = {"slug": ("firstname", "lastname")}
admin.site.register(Member, MemberAdmin)
With prepopulated_fields
, Django will auto-generate slugs from the firstname
and lastname
fields when you save a record. For example, Emil Refsnes becomes emil-refsnes
.
Step 3: Update the Template
Next, we update the template so that the member detail links use slugs instead of IDs.
In your all_members.html
template:
xml{% extends "master.html" %}
{% block content %}
<div class="mycard">
<h1>Members</h1>
<ul>
{% for x in mymembers %}
<li onclick="window.location = 'details/{{ x.slug }}'">
{{ x.firstname }} {{ x.lastname }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
Now, when you click a member, the URL will include the slug instead of a numeric ID.
Step 4: Update URLs
We also need to adjust the urls.py
file so that it fetches members using slugs. Change the path
configuration like this:
pythonfrom django.urls import path
from . import views
urlpatterns = [
path('', views.main, name='main'),
path('members/', views.members, name='members'),
path('members/details/<slug:slug>', views.details, name='details'),
path('testing/', views.testing, name='testing'),
]
Here, <slug:slug>
tells Django to expect a slug instead of an integer ID.
Step 5: Update the View
Finally, update the view function in views.py
to fetch member details using the slug.
pythonfrom django.http import HttpResponse
from django.template import loader
from .models import Member
def members(request):
mymembers = Member.objects.all().values()
template = loader.get_template('all_members.html')
context = { 'mymembers': mymembers }
return HttpResponse(template.render(context, request))
def details(request, slug):
mymember = Member.objects.get(slug=slug)
template = loader.get_template('details.html')
context = { 'mymember': mymember }
return HttpResponse(template.render(context, request))
Now, instead of retrieving member data by ID, Django will search by the slug field.
Step 6: Run the Server and Test
Once everything is set up, run your server again:
bashpython manage.py runserver
Visit:http://127.0.0.1:8000/members/
Click a member, and you’ll see a clean, user-friendly slug URL. 🎉
Final Thoughts
Django’s SlugField is a small but powerful feature that transforms the way URLs look and perform. Clean URLs improve trust, usability, and SEO results, making them essential for modern Django projects.
👉 If you’re building blogs, e-commerce sites, or portfolios, using slugs is a must. They make your web app more professional, easier to share, and loved by both users and search engines.
Leave a Reply