Search code examples
djangoslug

How to auto-update the slug field in Django admin site?


I know how to auto-populate the slug field of my Blog application from post's title, and it works fine.

But if I edit the title the slug field is not changing.

Is there any way to have it updated automatically?

I use Django's admin site.

Thanks.


Solution

  • from django.utils.text import slugify    
    class Category(models.Model):
        category_name = models.CharField(max_length=100)
        slug_category = models.SlugField(default='',editable=False, null=True,blank=True,max_length=250)  
    
        def __str__(self):
            return "%s" %(self.category_name)
        
        def save(self, *args, **kwargs):
            value = self.category_name[0:250]
            self.slug_category = slugify(value, allow_unicode=True)
            super().save(*args, **kwargs)
    

    May be this is usefull..