简体   繁体   中英

Adding Unique Slug in Django

I'm trying to add a slug field in my school project, Here's what I tried in my model,

def pre_save_receiver(sender, instance, *args, **kwargs):

   slug = slugify(instance.title)
   exists = Data.objects.filter(slug=slug).exists()
   if exists:
      instance.slug = "%s-%s" % (slug, instance.id)
   else:
      instance.slug = slug



pre_save.connect(pre_save_receiver, sender=Data)

Everything is working fine but the problem is that it's adding ID in slug field behind even if it's Unique. How can I fix that?

Model at least has the following:

class YourModel(models.Model):
    title   = models.CharField(max_length=120)
    slug  = models.SlugField(blank=True, null=True)

You need to create a file named utils in your app folder which contains the following code:

utils.py

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:
        slug = slugify(instance.title)

    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

Models.py

from django.db.models.signals import pre_save, post_save

from .utils import unique_slug_generator

def pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
    instance.slug = unique_slug_generator(instance)

pre_save.connect(pre_save_receiver, sender=YourModel)

You are trying to get id of non-existing model. pre_save signal calls before model saves. Instead of pre_save use post_save signal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM