Created
July 12, 2019 18:44
-
-
Save aballah-chamakh/e53c67417a3dc500203cd3494ecb98b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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