Table of contents
1.
Introduction
2.
What is SlugField in Django?
3.
Why we should use Slugs
4.
Add the SlugField inside Django Model
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Add the SlugField inside Django Model

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

We want to access different pages, posts, products, etc., with varying URLs (Uniform Resource Locator) in our project. How can we achieve this? The answer is quite simple; we can use slugs for that.

A Slug is a shorthand for something containing only letters, numbers, hyphens, or underscores. We use slugs in the URLs to access different things on the website. For example, in a blog URL:

https://www.codingninjas.com/studio/a-random-blog/

 

Here, the last data Coding Ninjas Studio/a-random-blog is the slug.

This article will learn how to add the slugField inside Django Model. So, let's get started.

What is SlugField in Django?

SlugField is a way to create a URL using the available data. We may generate the URL using the title, id, etc., of the page or post at our convenience. Let's see one example of Slugfield inside Django model to understand better.

Let's assume we have a blog titled "CodingNinjas is best" and primary id= 5. We may create the slug for the blog in different ways like:

https://www.codingninjas.com/blog/5/

 

Here, we created the slug for the blog using the primary id. However, the content writers and readers may find it challenging to recognize the article with its URL. 

But if we create the slug for the blog using its title.

https://www.codingninjas.com/blog/CodingNinjas-is-best/

 

The above URL is easy to read and recognize the post or pages. SlugField helps generate these types of URLs.

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:

  1. First, we need to create a Django model.
  2. Next, we need to find a way to convert the title into a slug every time a new model instance is created.
  3. 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.

Live masterclass