0 day streak
python / intermediate
Snippet

Django Signal for Automatic Slug Generation

Django signals allow you to execute code when certain events occur in the ORM. This pre_save signal automatically generates a unique URL-friendly slug from the product name, handling duplicates by appending incremental numbers.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.text import slugify
from .models import Product
@receiver(pre_save, sender=Product)
def generate_slug(sender, instance, **kwargs):
if not instance.slug:
base_slug = slugify(instance.name)
slug = base_slug
counter = 1
while Product.objects.filter(slug=slug).exists():
slug = f"{base_slug}-{counter}"
counter += 1
instance.slug = slug
django
Breakdown
1
@receiver(pre_save, sender=Product)
Decorator registers this function to run before a Product instance is saved
2
slugify(instance.name)
Django utility converts 'iPhone 15 Pro' to 'iphone-15-pro' for URL compatibility
3
while Product.objects.filter(slug=slug).exists():
Check if generated slug already exists in database to ensure uniqueness
4
slug = f"{base_slug}-{counter}"
Append counter suffix to create unique slug like 'iphone-15-pro-2'