Why we should use Slugs
Having properly formatted slugs for the web pages are important because of the following reasons:
- Search engines use the URLs of the web page alongside the title, content and metadata to detect where the web page should rank in the search results.
- Google recommends using hyphens (-) to separate words in the Slugs since they treat them as whitespaces.
- We should keep our slugs short and concise fro a better SEO(Search Engine Optimization) ranking.
Add the SlugField inside Django Model
This section will create a Django model and add the slugField inside Django model. We will do that in the following steps:
- First, we need to create a Django model.
- Next, we need to find a way to convert the title into a slug every time a new model instance is created.
- Finally, we will check and modify the slug if it is already taken.
So, let's start creating a Blog model to work on in the models.py file,
from django.db import models
# Make the Blog model here.
class Coding Ninjas StudioBlog(models.Model):
title = models.CharField(max_length = 250)
slug = models.SlugField(max_length = 250, null = True, blank = True)
description = models.TextField()
date= models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.title

You can also try this code with Online Python Compiler
Run Code
The above code will create a Coding Ninjas StudioBlog model with fields as title, slug, description and date. We also added the __str__(self) function to change the object display name of the model.
Now, let's try to find a way to convert the title into a slug automatically. Moreover, we want this script to trigger every time a new instance of the Coding Ninjas StudioBlog model is created. For this purpose, we will use Slugify and signals in Django,
We need to create a new file utils.py in the same directory where we have settings.py and add the following code,
import string, random
from django.utils.text import slugify
def random_string(n = 12, chars = string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(n))
def unique_slug(instance, unq_slug = None):
if unq_slug is not None:
slug = unq_slug
else:
slug = slugify(instance.title)
if_exists = Klass.objects.filter(slug = slug).exists()
Klass = instance.__class__
length = Klass._meta.get_field('slug').max_length
slug = slug[:length]
if if_exists:
new_slug = "{slug}-{randomstr}".format(
slug = slug[:length-5], randomstr = random_string(n=4))
return unique_slug(instance, unq_slug = unq_slug)
return slug

You can also try this code with Online Python Compiler
Run Code
The unique_slug function will return a unique slug for the blog with its title and some random string (if required) in the above code.
Note: We need to execute some changes or actions when there is a modification in the Django model's instance. Django provides us with a great way to handle this situation by using Signals. It helps de-coupled applications get notified when actions occur anywhere in the framework.
So, we will create a function that runs when a signal calls it in the same file where we have our model, i.e., in the models.py file,
from django.dispatch import receiver
from django.db.models.signals import pre_save
@receiver(pre_save, sender=Post)
def pre_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug(instance)

You can also try this code with Online Python Compiler
Run Code
We created a pre_receiver function outside the Coding Ninjas StudioBlog model in the above code, which will run when a signal calls it.
Now we just need to add the path in the urls.py file by writing the following code,
def blog_url(request, slug):
object = Post.objects.filter(slug__iexact = slug)
if object.exists():
object = object.first()
else:
return HttpResponse('Opps… No Post Found')
context = {
'blog': object return render(request, blogs/blog.html', context)
}

You can also try this code with Online Python Compiler
Run Code
After adding the URL path, we are ready to view the article by visiting the URL https://localhost:8000/blogs/your-blog-title/, and it will display the blogs/blog.html template.
Frequently Asked Questions
1. How are whitespaces treated differently in slugs and URLs?
Ans. Well, 'a random title' is a valid slug while https//localhost/a random title/ is an invalid URL. So whitespaces in a URL are replaced by '%20', making the URL https//localhost/a%20random%20title/.
2. What is Slugify?
Ans. Slugify converts a string into a URL slug by:
- Converting it to ASCII if the allow_unicode = false.
- Converting alphabets to lowercase and removing anything other than alphabets, numbers, underscore, hyphens or whitespaces.
- Converting whitespaces or repeated dashes with a single dash.
Key Takeaways
This article taught us how to add the SlugField inside Django Model. We created a Django blog model and wrote the code to add the Slugfield inside Django Model and validate if the slug is unique.
Don't stop here. Check out the blogs Best Django Books, Top 30 Basic Django Interview Questions: Part 1, and Top 30 Intermediate Django Interview Questions: Part 2.
We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.