How to generate slug based on title of post in django?

Question:

I am working on a project where I want to create a slug for each post based on its title. Is it possible to generate a slug in such a way that it will be unique to the post, but will not change even if the title of the post is changed? I am using the model provided in the file ‘model.py’. Can you provide guidance on how to accomplish this?

class Post(models.Model):

    
    username = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    description = models.CharField(('Description'),max_length=250)
    title = models.CharField(('Content Title'), max_length=250)
    create_date = models.DateTimeField(default = timezone.now)
    image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None)
    slug = (title)

    def __str__(self):
        return self.title
Asked By: Ahmed Yasin

||

Answers:

I recommend checking out the Django documentation for slugify. You will need to override the save method of your model to do this, so your new code will most likely look something like this:

from django.utils.text import slugify
slug=models.SlugField()

def save(self,*args,**kwargs):
    self.slug=slugify(self.title)
    super(Post,self).save(*args,**kwargs)

I would keep in mind the unique parameter that you can set to either true or false in your slugfield.

Answered By: Graham13579