Skip to content

Instantly share code, notes, and snippets.

@cavb
Last active June 11, 2018 18:25
Show Gist options
  • Save cavb/b58df2fc5e516dfc8c23ddd302fd2b34 to your computer and use it in GitHub Desktop.
Save cavb/b58df2fc5e516dfc8c23ddd302fd2b34 to your computer and use it in GitHub Desktop.
Django pre_save create unique slug
@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