Reputation: 347
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.
Upvotes: 4
Views: 1030
Reputation: 2235
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..
Upvotes: 4
Reputation: 540
@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",)}
Upvotes: 3