Creating unique slugs will help us to create beautiful URLs in Django websites.
/* URL with post id or record id */
https://example.com/article/123
/* URL with unique slug */
https://example.com/article/post-slug
While creating the Model itself, we need to create a field for slug as follows
post_slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True)
Write a save() function to process the slug while creating the post. Use following code to generate unique slug for a post when created.
def save(self, *args, **kwargs):
# Check if slug field is empty
if self.speaker_slug is None:
# Function to create slug for current post based on post title
slug = slugify(self.speaker_first_name + ' ' + self.speaker_last_name)
# Check if this slug name already exists for any other posts
temp = Speaker.objects.all().filter(speaker_slug=slug)
if temp.count() == 0:
# If no post record have this slug, then assign this slug to the current post
self.post_slug= slug
else:
# If the slug we got already exists to some other post record. Loop through to add numbers at end
flag = False
# Initialize with 2 so if example slug already exists, we start with assigning example-2
count = 2
# Loop through the same process of generating unique slug
while flag == False:
# Function to create slug for current post record based on post title and count
slug = slugify(self.speaker_first_name + ' ' + self.speaker_last_name + ' ' + str(count))
# Check if this new slug too exists for some other post record
if self.check_if_slug_exists(slug) == False:
# Assign this slug to the current post record and break the loop
flag = True
self.post_slug = slug
else:
# Increase the count and try next version of the slug starting loop again.
count = count+1
# Save all the changes to the post record
super(Speaker, self).save(*args, **kwargs)
This example is based on class based views (CBV) in Django.