class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
For pre-1.0:
slug = models.SlugField(prepopulate_from=('title',))
should work just fine
For 1.0, use camflan's
for Admin in 1.0, you'd need to use
prepopulated_fields = {'slug':('title',),}
in your admin.py
Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.
Outside of admin, you can use the slugify
function in your views.
In templates, you can use the |slugify
filter.
Outside the admin, see this django snippet. Put it in your .save()
, and it'll work with objects created programmatically. Inside the admin, as the others have said, use prepopulated_fields
.
You can also use pre_save django signal to populate slug outside of django admin code. See Django signals documentation.
Ajax slug uniqueness validation will be useful too, see As-You-Type Slug Uniqueness Validation @ Irrational Exuberance