Search code examples
pythonhtmldjangoslug

How to auto generate slug in Django


Trying to build a blog,
I need to auto-generate the slug for making the URL based on the article title.

many thanks


Solution

  • there are multiple way, i have explained few simple and easy

    you can add via admin.py

    class ModelAdmin(admin.ModelAdmin):
        prepopulated_fields = {"slug": ("your_field_name",)}
    
    admin.site.register(Model, ModelAdmin)
    

    you can use slugify on model save method

    example

    class Test(models.Model):
        q = models.CharField(max_length=30)
        s = models.SlugField(editable=False) # hide from admin
    
        def save(self):
            if not self.id:
                self.s = slugify(self.q)
    
            super(Test, self).save()