How to create a Django model with a SlugField and editable option



Image not found!!

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:

python
from 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:

  • We have a model called 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.
  • The unique=True option ensures that each slug value is unique across all instances of YourModel.
  • The 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.