Login

a better Django Slug Unique Generator

Author:
ParsaFakhar
Posted:
October 17, 2019
Language:
Python
Version:
Not specified
Tags:
django slug url
Score:
1 (after 1 ratings)

let say the user chooses the name "Elsa Frozen" now his slug would be "Elsa-Frozen-5"

it means 4 other people have used the same header now he can go to url: "your website.com/Elsa-Frozen-4" to see other people's Post

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.utils.text import slugify

class Post(models.Model):
    header = models.CharField(max_length=50)
    slug = models.SlugField(unique=True, db_index=True)

    def __str__(self):
        return self.header

    def get_absolute_url(self):
        return reverse("post-detail", kwargs={"slug": self.slug})


def unique_slug_generator(instance):
    constant_slug = slugify(instance.header)
    slug = constant_slug
    num = 0
    Klass = instance.__class__
    while Klass.objects.filter(slug=slug).exists():
        num += 1
        slug = "{slug}-{num}".format(slug=constant_slug, num=num)
    return slug

def pre_save_reciever(sender, instance, *args, **kwargs):
    if not instance.slug or instance.header != Post.objects.filter(slug=instance.slug):
        instance.slug = unique_slug_generator(instance)

pre_save.connect(pre_save_reciever, sender=Post)

More like this

Comments

Please login first before commenting.