Ensuring User-Friendly URLs: Populating Django's SlugField from CharField
Using the save() method:
This approach involves defining a custom save()
method for your model. Within the method, you can utilize the django.utils.text.slugify
function to convert the desired CharField
(e.g., title
) into a slug and assign it to the SlugField
(e.g., slug
). Here's an example:
from django.db import models
from django.utils.text import slugify
class MyModel(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True) # Ensure unique slugs
def save(self
python django slug