Add the slug field inside Django Model

In this tutorial, we are going to learn about the SlugField in Django.


SlugField is a way to generate a URL using the data which we already have. You can generate URL using your title of the post or page. Let's see one detailed example.

Let's say we have an article with name This is from Tutorialspoint with id = 5. Then we can have URL as It's difficult for the content writers to recognize the article with the previous URL. But, if you have a URL like, then it's easy for us to identify the piece. So, SlugField is used to generate those types of URLs'.

Let's see the code of our post model. Compare your model with the following model.

   ('draft', 'Draft'),
   ('published', 'Published'),
class Article(models.Model):
   title = models.CharField(max_length = 250)
   slug = models.SlugField(max_length = 250, null = True, blank = True)
   text = models.TextField()
   published_on = models.DateTimeField(auto_now_add = True)
   updated_time = models.DateTimeField(auto_now = True)
   status = models.CharField(max_length = 10, choices = CHOICES, default ='draft')
class Meta:
   ordering = ('_Published_At', )
   def __str__(self):
return self.title

Now, we will add SlugField to our project. So, it automatically generates the URLs according the title.

Create a file called in the project level directory. We have to generate URL every time invoke the Post model. To achieve that, we need signals.

import string
   from django.utils.text import slugify
   def get_random_string(size = 10, chars = string.ascii_lowercase + string.digits
   return ''.join(random.choice(chars) for _ in range(size))
def get_slug(instance, slug = None):
   if slug is not None:
      slug_two = slug
      slug_two = slugify(instance.title)
   Klass = instance.__class__
   is_exists = Klass.objects.filter(slug_two = slug_two).exists()
   if is_exists:
      slug_two = "{slug_two}-{random_string}".format(slug_two = slug_two, ran
      string = get_random_string(size = 5))
   return get_slug(instance, slug = slug)
return slug_two

Add the following code at the end of the file

def pre_save_receiver(sender, instance, *args, **kwargs):
if not instance.slug_two:
instance.slug_two = get_slug(instance)
pre_save.connect(pre_save_receiver, sender = Article)

In the edit the path like path('posts/', post). Edit the according to the code.

def article(request, slug):
obj = Article.objects.filter(slug__iexact = slug)
   if obj.exists():
      obj = obj.first()
      return HttpResponse('Article Not Found')
context = {
   'article': obj
return render(request, 'posts/post.html', context)

Updated on: 21-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started