When using Django to build web applications, you may want to associate each of your entries in the database with a slug that is human-readable. To do this, using a slug field is a good solution. Slugs are commonly used for URL addresses, SEO, and user-friendly links.
The slug field can help you to use a title or any other field in your model to create a unique key that can easily be used in URLs. However, a question that arises is how these slugs are created and added to your models?
In Django, you can automatically generate a slug based on another field. For example, suppose you have a model for your blog and you want to create a slug based on the title, you can easily achieve this. This task is quite simple, and Django provides you with suitable tools for finishing this task.
To add a slug field to your model, you should start by using the SlugField
class. This field is very similar to other text fields but by default is designed to accept only valid characters for a URL. You can use suitable examples of slugs based on a field in your model creation.
Furthermore, using a user case example, we will observe how to add and automatically generate a slug based on the title in a blog model.
Example Code for Creating a Slug Field in Django Model
from django.db import models
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True, blank=True)
content = models.TextField()
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Article, self).save(*args, **kwargs)
Line-by-Line Description of the Code
from django.db import models
This line imports the
models
module from Django, which allows us to create database models.from django.utils.text import slugify
This line imports the utility that will be used to convert strings into slugs.
class Article(models.Model):
This line defines a class named
Article
that inherits from models.Model
. This class defines our model.title = models.CharField(max_length=200)
This line defines a character field for the title of the article, which can contain up to 200 characters.
slug = models.SlugField(unique=True, blank=True)
This line defines a slug field that is unique and can be left blank.
content = models.TextField()
This line defines a text field for the article content without any limit on the number of characters.
def save(self, *args, **kwargs):
This line defines a method named
save
that allows for custom save functionality.if not self.slug:
This line checks whether the slug field has been set.
self.slug = slugify(self.title)
If the slug has not been set, it creates a slug based on the article title.
super(Article, self).save(*args, **kwargs)
This line calls the original save method from the parent class to save the model to the database.