4

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.

Omid Shojaee
  • 333
  • 1
  • 4
  • 20

2 Answers2

3

@Omid Shojaee- Have a look at the following code. You can use the prepopulated_fields

class CategoryAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "name",
        "slug",
        "is_active",
    )
    prepopulated_fields = {"slug": ("name",)}
SDRJ
  • 532
  • 3
  • 11
3
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..

Pradip Kachhadiya
  • 2,067
  • 10
  • 28
  • 1
    Thanks a lot. While this is not auto-updating the slug filed, it does work after saving the changes. Thanks again. – Omid Shojaee Feb 17 '21 at 18:57