In Django, a “slug” is a short label used to identify a model instance in a URL-friendly manner. It’s often used to create human-readable URLs for objects, especially when those objects have a title or name. Slugs typically contain only lowercase letters, numbers, hyphens, and underscores.
Here’s an example of how to use a slug field in a Django model:
Example Scenario: Let’s say you have a model called Article
with a title, and you want to generate a slug for each article based on its title.
Step 1: Import Required Modules: In your models.py
file, import the necessary modules:
from django.db import models from django.utils.text import slugify # To create slugs from text
Step 2: Define the Model with Slug Field: Define your model and include a SlugField
to store the slug:
class Article(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) # Slug field def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) # Generate slug from title super().save(*args, **kwargs) def __str__(self): return self.title
In this example, the SlugField
is used to store the slug. The save
method is overridden to automatically generate the slug from the title if it’s not provided. The slugify
function is used to convert the title into a slug-friendly format.
Step 3: Use the Model: Once you’ve defined the model, you can create instances of the Article
model and access the slug field:
article = Article(title='Django Slug Example') article.save() print(article.title) # Output: Django Slug Example print(article.slug) # Output: django-slug-example
Step 4: Include the Slug in URLs: In your urls.py
file, you can include the slug as part of the URL patterns:
from django.urls import path from .views import ArticleDetailView urlpatterns = [ path('<slug:slug>/', ArticleDetailView.as_view(), name='article_detail'), # ... ]
Here, the slug is captured from the URL and passed to the ArticleDetailView
to fetch the corresponding article.
Using slugs in Django allows you to create user-friendly and SEO-friendly URLs that are easy to understand and share.