In Django, you can set a default value for a model field, including a SlugField
, by using the default
parameter when defining the field in your model. Here’s how you can do it:
Let’s say you have a model called Article
with a title
field and you want to generate a slug from the title with a default value.
from django.db import models
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True, default='default-slug')
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def __str__(self):
return self.title
SlugField
with default
: default='default-slug'
: This sets a default value for the slug
field if no value is provided.
Override save
method: In the save
method, we check if the slug
field is empty (if not self.slug:
). If it is, we generate a slug from the title
using slugify
.
blank=True: The blank=True
argument allows the field to be optional in forms. This is useful because the save
method will generate the slug if it’s not provided.
Notes
If you want to ensure that the slug
is always unique, you can set unique=True
on the SlugField
.The default
value could be a static string (as shown) or dynamically generated in some cases. However, be cautious with dynamic defaults to ensure the uniqueness of the slugs.