tag (slugify)


call slugify template tag in django model or view May

Edited: 6.1.2011 - fixed typo

Sometimes I need to slugify something within a django model or view file. Django already has this functionality written as a template filter, and you can reuse this outside of the templates. You can import slugify into your python code like so:

from django.template.defaultfilters import slugify


Which then allows you to write something like:

class Custom(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(blank=True) def save(self): self.slug = slugify(self.name) super(Custom, self).save()

However, if you need this type of functionality depending on your situation it might be easier to set this up using the django admin prepopulated_fields option.

# models.py
class Custom(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()

# admin.py
class CustomAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}

admin.site.register(Custom, CustomAdmin)

This will auto-populate the slug field while you type the name within the django admin.