What is Slug in Django?


A Slug in Django is a string that contains only letters, numbers, underscores, or hyphens. For examples, 'hello-world', 'what-is-slug', 'learn-django', etc.

Slugs are generally used in URLs. For example, in the URL of this page:


The slug-django is a slug.

A URL can contain multiple slugs. For example, the following URL has two slugs:

# python-programs
# online-ide

Convert String to Slug in Django

Using the slugify() method of django.utils.text module, you can easily convert a string into a URL slug.

>>> from django.utils.text import slugify
>>> s = slugify('Hello World')
>>> s

Store Slug in Database in Django

In Django, you can easily store a slug in a SlugField column of the database table.

from django.db import models

class Post(models.Model):
    title = models.CahrField(max_length=100, default='')
    content = models.TextField(default='')
    slug = models.SlugField(unique=True, max_length=100)

Leave a Reply

Your email address will not be published. Required fields are marked *