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



Image not found!!

To create a Django model with a SlugField and a default option, you can set the default parameter when defining your model field. 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 default option set to automatically generate a slug from the title slug = models.SlugField(max_length=150, unique=True, default='') 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.
  • The default option is set for the slug field. In this case, we set it to an empty string ''.
  • 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.

With the default option set to '', the slug field will default to an empty string if no value is provided during the creation of a new instance of YourModel. Then, in the save() method, a slug will be automatically generated based on the title field if the slug field is empty.