Last active
October 15, 2022 12:25
-
-
Save Olamidun/4f97f7c22b33ea721ddf48253ce27877 to your computer and use it in GitHub Desktop.
Sample Slug Code Snippet
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
class Farmer(models.Model): | |
#existing fields | |
slug = models.SlugField(max_length=500, null=True) | |
def __str__(self): | |
# The string representation for farmers | |
pass | |
# This can also be in the signals | |
@receiver(pre_save, sender=Farmer) | |
def pre_save_receiver(sender, instance, *args, **kwargs): | |
if not instance.slug: | |
instance.slug = unique_farmer_slug_generator(instance) | |
def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): | |
return ''.join(random.choice(chars) for _ in range(size)) | |
def unique_farmer_slug_generator(instance, new_slug = None): | |
if new_slug is not None: | |
slug = new_slug | |
else: | |
slug = slugify(f"{instance.first_name} {instance.last_name}") | |
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 = 10)) | |
return unique_farmer_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