- Create a slug field in your Django model:
from django.db import models
from django.utils.text import slugify
class YourModel(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True, blank=True)
- Override the
save
method in your model to automatically generate the slug from the title:
from django.db import models
from django.utils.text import slugify
class YourModel(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True, blank=True)
def save(self, args, *kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(YourModel, self).save(args, *kwargs)
- Use the slug field in your URLs or any other place where you need a unique identifier for the model instance.