Login

a better Django Slug Unique Generator

Author:
ParsaFakhar
Posted:
October 17, 2019
Language:
Python
Version:
Not specified
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.