Skip to content

Instantly share code, notes, and snippets.

@raykipkorir
Last active May 26, 2024 09:55
Show Gist options
  • Save raykipkorir/c010d3a875cdcd48ed48a5f15aa56195 to your computer and use it in GitHub Desktop.
Save raykipkorir/c010d3a875cdcd48ed48a5f15aa56195 to your computer and use it in GitHub Desktop.
Unique slug generator.
import random
import string
from django.utils.text import slugify
# generate a rondom string to be appended to slug if the slug queried already exists
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# generate a unique slug based on post title
def unique_slug_generator(instance, new_slug: str|None = None) -> str:
if new_slug is None:
slug = slugify(instance.title)
else:
slug = new_slug
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
random_str = random_string_generator(size=4)
new_slug = f"{slug}-{random_str}"
return unique_slug_generator(instance, new_slug)
return slug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment