Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

slug

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.

like image 371
Omid Shojaee Avatar asked Oct 29 '25 08:10

Omid Shojaee


2 Answers

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..

like image 135
Pradip Avatar answered Oct 31 '25 02:10

Pradip


@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",)}
like image 30
SDRJ Avatar answered Oct 31 '25 01:10

SDRJ