To create a Django model with a SlugField
and an editable option, you can simply define your model class in your Django app's models.py
file and include a SlugField
with the desired options. The editable
option is True
by default, but I'll show you how to explicitly set it for clarity. Here's an example:
pythonfrom django.db import models
from django.utils.text import slugify
class YourModel(models.Model):
# Your other fields
title = models.CharField(max_length=100)
# Slug field with editable option set to True
slug = models.SlugField(max_length=150, unique=True, editable=True)
def save(self, *args, **kwargs):
# Automatically generate slug from the title if not provided
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
def __str__(self):
return self.title
In this example:
YourModel
with a title
field of type CharField
and a slug
field of type SlugField
.editable=True
is explicitly set for the slug
field, although it's not necessary since it's the default behavior.unique=True
option ensures that each slug
value is unique across all instances of YourModel
.save()
method is overridden to automatically generate a slug from the title using Django's slugify()
function if a slug is not provided.You can then run python manage.py makemigrations
and python manage.py migrate
to apply these changes to your database schema.