Post Slugs Update (we've been there, haven't we ?)
Post slugs have been updated
What’s new ?
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:
1def save(self, *args, **kwargs): 2 if not self.slug: 3 self.slug = slugify(self.title) 4 return super().save(*args, **kwargs)
Basically if the slug doesn’t exist create one based on the title.
The code is now:
1def save(self, *args, **kwargs): 2 max_length = Post._meta.get_field('slug').max_length 3 self.slug = orig = slugify(self.title)[:max_length] 4 for x in itertools.count(2): 5 if self.pk: 6 if Post.objects.filter(Q(slug=self.slug), 7 Q(author=self.author), 8 Q(id=self.pk), 9 ).exists(): 10 break 11 if not Post.objects.filter(slug=self.slug).exists(): 12 break 13 14 # Truncate & Minus 1 for the hyphen. 15 self.slug = "%s-%d" % (orig[:max_length - len(str(x)) - 1], x) 16 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