Hey dev.to community!
Which URL is easy to remember? This products/wireless-headphone/
or this products/uuidxyz2292992/
? For me products/wireless-headphone/
url is easy to note.
🌟 What is Slugs?
A slug is a URL-friendly version of a string, typically derived from a title, description or name. It only contains lowercase letters, numbers, and hyphens. This term ‘slug’ comes from newspaper publishing, where it referred to a short name used to identify a story.
Example: "Django Slugs: Complete Guide" → django-slugs-complete-guide
🌟 Why use Slugs?
SEO Benefits:
-
/api/products/wireless-bluetooth-headphones/
is much better than/api/products/47/
- Search engines love descriptive URLs
User Experience:
- URLs are readable and shareable
- Users can guess what the URL might be and can modify URLs to find similar products
- More professional-looking API
Security:
- Doesn't expose your database ID sequence
- Harder for people to guess other product IDs
📌 Basic Slug Implementation
Django makes working with slugs incredibly straightforward with the built-in SlugField
:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
description = models.TextField()
def __str__(self):
return self.name
📌 Auto-Generate Slugs
Manual entry in Slug field can get tedious, we can automate this by using Django’s slugify
function:
from django.db import models
from django.utils.text import slugify
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
description = models.TextField()
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
When we create a new product with name ‘Python Best Practice Book’, the slug automatically becomes python-best-practice-book
.
📌 Handling Duplicate Slugs
What happens when two post have the same title? We need to handle duplicates gracefully:
from django.db import models
from django.utils.text import slugify
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
description = models.TextField()
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
unique_slug = self.slug
counter = 1
while Product.objects.filter(slug=unique_slug).exists():
self.slug = f"{unique_slug}-{counter}"
counter += 1
super().save(*args, **kwargs)
This creates slugs like headphone
, headphone-1
, headphone-2
to handle duplicate names.
🖌️ End Notes
To make our project or application more professional and top notch, one should definitely utilise Django’s slug functionality wherever we can.
Let me know, in the comments about your project where you discovered slug for the first time and how it improved you application? Or may be share some of the advanced slug techniques that you have used in your project.
Reference: https://learndjango.com/tutorials/django-slug-tutorial
See you’ll next time.. bye 👋
Top comments (0)