Last active
June 11, 2018 18:25
-
-
Save cavb/b58df2fc5e516dfc8c23ddd302fd2b34 to your computer and use it in GitHub Desktop.
Django pre_save create unique slug
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
@receiver(pre_save, sender=Course) | |
def create_slug(sender, instance, *args, **kwargs): | |
instance.slug = orig = slugify(instance.name) | |
if Course.objects.filter(slug=instance.slug).exists(): | |
# Creates a unique slug, adding -number when its already used. | |
for x in itertools.count(1): | |
if not Course.objects.filter(slug=instance.slug).exists(): | |
break | |
instance.slug = '%s-%d' % (orig, x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment