Slugify when editing an entry


Adding something like prepopulated_fields = {'slug': ('title',)} to the model admin, Django populates the slug field with the slugified string of title field as I type in (in real-time).

But this only works when adding a new entry and not when editing an existing entry.

Overriding the save() method is not what I’m looking for. I’m looking for real-time population of the slug field with the slugified string of the title field when I’m editing an entry.

What baffles me is that both add and change forms load prepopulate.js, so the function is available?

Probably. But it’s an explicit decision made to not provide that functionality.

From the docs for prepopulated_fields:

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).

Thanks and I understand the rationale behind it, but what if I need it?

Then it would be up to you to implement it.

You could find where in the admin code that it checks to see if the existing target field has data or not, and figure out how to override it.

A rather cursory look into the admin shows that the change_form.html template renders a tag named {% prepopulated_fields_js %}. This tag is defined in django.contrib.admin.templatetags.admin_modify, and ends up rendering the template prepopulated_fields_js.html located in django.contrib.admin.templates.admin.

There are a number of other references to “prepopulated_fields” through different parts of the admin with a number of different functions involved.

I tried looking for whatever might be used to determine whether the target field already has data, but I didn’t see anything obvious.

Or, you might be able to create your own function that will render that template tag - or your substitute - regardless of the existing status of the field.

That’s my exact problem. If I found that it would be very easy to disable it and have it work in both cases.