Skip to content

Instantly share code, notes, and snippets.

@aballah-chamakh
Created July 12, 2019 18:44
Show Gist options
  • Select an option

  • Save aballah-chamakh/e53c67417a3dc500203cd3494ecb98b2 to your computer and use it in GitHub Desktop.

Select an option

Save aballah-chamakh/e53c67417a3dc500203cd3494ecb98b2 to your computer and use it in GitHub Desktop.
import random
import string
from django.utils.text import slugify
def random_string_generator(size=5, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def unique_slug_generator(instance, new_slug=None):
if new_slug is not None:
slug = new_slug
else:
if hasattr(instance,'title') :
slug = slugify(instance.title)
else :
slug = slugify(instance.user.username)
Model = instance.__class__
qs_exists = Model.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug,
randstr=random_string_generator(size=4)
)
return unique_slug_generator(instance, new_slug=new_slug)
return slug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment