Post Slugs Update (we've been there, haven't …

Blog Updates

Post #207

EN

Post Slugs Update (we've been there, haven't we ?)

Sunday, 17 January 2021 00:54:17 by Khodok

2 min read

Post slugs have been updated

What’s new ?

  • Nothing

What changed ?

  • Post slugs changed
    Slugs are based off the title, which means if the title is “This post will talk about Banana Split”, the post slug will be “this-post-will-talk-about-banana-split”.
    There’s a big problem with that, if two titles are the same (which I want it to be possible, for different reasons but also because I don’t have much more ideas on how to name the Wednesday Posts), the two slugs will bug because they’ll be the same, and slugs HAVE to be different (for a few reasons, first: they kinda act like an ID (it’s the only other thing that can be used as an ID with Django), second: if two posts have the same slug… how would you go to one or the other ? well you couldn’t).

Good news !

the old code for auto generated slugs was:

1
2
3
4
def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        return super().save(*args, **kwargs)

Basically if the slug doesn’t exist create one based on the title.

The code is now:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def save(self, *args, **kwargs):
        max_length = Post._meta.get_field('slug').max_length
        self.slug = orig = slugify(self.title)[:max_length]
        for x in itertools.count(2):
            if self.pk:
                if Post.objects.filter(Q(slug=self.slug),
                                       Q(author=self.author),
                                       Q(id=self.pk),
                                       ).exists():
                    break
            if not Post.objects.filter(slug=self.slug).exists():
                break

            # Truncate & Minus 1 for the hyphen.
            self.slug = "%s-%d" % (orig[:max_length - len(str(x)) - 1], x)
        return super().save(*args, **kwargs)

Meaning even more basically:
If the post doesn’t have a slug, create one, but if the slug you’re trying to exist already exists, add a number after it, starting with 2 (so if the slug “this-post-will-talk-about-banana-split” exists, create “this-post-will-talk-about-banana-split-2”), and voilà, we can have two times the same title but the auto slug will be different 😄

Comments

Please Log in to leave a comment.


This post has 0 comments.