In Django, a SlugField
is often used to store URL-friendly versions of a string. It is commonly used to generate human-readable and SEO-friendly URLs for your models. To create a Django model with a SlugField
, you can follow these steps:
Import the necessary modules:
Import the models
module from the django.db
package.
pythonfrom django.db import models
Define your model:
Create a class for your model, subclassing models.Model
. Add the fields you need, including the SlugField
for the URL-friendly version.
pythonclass YourModel(models.Model):
# Your other fields go here
title = models.CharField(max_length=255)
content = models.TextField()
# Slug field for URL
slug = models.SlugField(max_length=255, unique=True)
In this example, replace YourModel
, title
, and content
with your actual model name and other fields.
Override the save
method:
You may want to override the save
method to automatically generate the slug when an instance is saved. You can use the slugify
function from django.utils.text
to create a slug from a string.
pythonfrom django.utils.text import slugify
class YourModel(models.Model):
# Your other fields go here
title = models.CharField(max_length=255)
content = models.TextField()
# Slug field for URL
slug = models.SlugField(max_length=255, unique=True)
def save(self, *args, **kwargs):
# Generate the slug from the title
self.slug = slugify(self.title)
super().save(*args, **kwargs)
This ensures that whenever an instance of YourModel
is saved, the slug
field is populated based on the title
.
Run migrations: After defining your model, run Django migrations to create the database table.
bashpython manage.py makemigrations python manage.py migrate
Now, you have a Django model with a SlugField
that will automatically generate a slug based on the title when an instance is saved. You can use this slug for creating SEO-friendly URLs for your model instances.