Skip to content

Instantly share code, notes, and snippets.

@tochimclaren
Created August 31, 2019 18:26
Show Gist options
  • Save tochimclaren/970f73bdfcc22e86198c4fb842f4ebe7 to your computer and use it in GitHub Desktop.
Save tochimclaren/970f73bdfcc22e86198c4fb842f4ebe7 to your computer and use it in GitHub Desktop.
Django Unique Slug Generator
import random
import string
from django.utils.text import slugify
def random_string_generator(size=10, 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:
# We are using .lower() method for case insensitive
# you can use instance.<fieldname> if you want to use another field
str = replace_all(instance.name.lower())
slug = slugify(str)
Klass = instance.__class__
qs_exists = Klass.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
def replace_all(text):
rep = {
'ı':'i',
'ş':'s',
'ü':'u',
'ö':'o',
'ğ':'g',
'ç':'c'
}
for i, j in rep.items():
text = text.replace(i, j)
return text
from django.dispatch import receiver
from django.db import models
from .slugify import unique_slug_generator
class TestModel(models.Model):
name = models.CharField(max_length=150)
slug = models.SlugField(unique=True, null=True, blank=True)
@receiver(models.signals.pre_save, sender=TestModel)
def auto_slug_generator(sender, instance, **kwargs):
"""
Creates a slug if there is no slug.
"""
if not instance.slug:
instance.slug = unique_slug_generator(instance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment