Skip to content

Instantly share code, notes, and snippets.

@jaradc
Last active April 20, 2022 22:26
Show Gist options
  • Save jaradc/e81ba39a688297ead0bb8134a9fec358 to your computer and use it in GitHub Desktop.
Save jaradc/e81ba39a688297ead0bb8134a9fec358 to your computer and use it in GitHub Desktop.
Simple-stupid way to guarantee slug uniqueness
from django.db import models
from django.utils.text import slugify
class Content(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
def save(self, *args, **kwargs):
# simple-stupid way to guarantee slug uniqueness
n = 1
base_slug = slugify(self.title)
slug = base_slug
while self.__class__.objects.filter(slug=slug).exists():
slug = f'{base_slug}-{n}'
n += 1
self.slug = slug
super().save(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment