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:

'https://pencilprogrammer.com/slug-django/'

The slug-django is a slug.

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

'https://pencilprogrammer.com/python-programs/online-ide/'
# 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
'hello-world'

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)

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply