Django Admin tip: Auto-generated slug content

With a single line you can save yourself the trouble of filling in the slug manually.

In this post I want to share super quick tip that can help you a lot, assuming you use Django Admin and at least some slug fields.

Slugs are these human readable parts of an URL, that also let you identify a piece of content. For example this URL: https://nemecek.be/blog/79/working-with-django-imagefield. The last part is a slug based on the post title "Working with Django ImageField".

The motivation for slugs is that URLs cannot contain spaces (among other characters) so we use process which is called "slugify" to turn a piece of text into valid slug.

Django offers a SlugField which will automatically validate its input to allow only slugs and you can use these as part of the URL.

And now we can finally move to the tip. Django ModelAdmin has setting called prepopulated_fields which is mainly there for automatic slug creation.

We can use an example from the official docs:

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

This will monitor the value of title input and automatically create slugified version with the help of JavaScript.

Django also makes sure to not automatically update this slug later on, because you probably don't want your slugs to change, since they can easily break existing URLs:

Prepopulated fields aren’t modified by JavaScript after a value has been saved. It’s usually undesired that slugs change (which would cause an object’s URL to change if the slug is used in it).

And that's it!

Filip Němeček profile photo

WRITTEN BY

Filip Němeček @nemecek_f

iOS blogger and developer with interest in Python/Django. Telling other devs' stories with iOS Chat.