Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sehrishnaz/2c02df2f1e6d64d1f688536d0f3edba1 to your computer and use it in GitHub Desktop.
Save sehrishnaz/2c02df2f1e6d64d1f688536d0f3edba1 to your computer and use it in GitHub Desktop.
Making Perfect Readable URL in Django Using Slug
import string, random
from django.utils.text import slugify
def random_string_generator(size=10, 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:
slug = slugify(instance.title)
Klass = instance.__class__
max_length = Klass._meta.get_field('slug').max_length
slug = slug[:max_length]
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug[:max_length - 5], randstr=random_string_generator(size=4))
return unique_slug_generator(instance, new_slug=new_slug)
return slug
@sehrishnaz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment