If you have started filling the database with data, you might have noticed that you have to manually enter values for the slug field. Luckily, Django has a feature to automatically populate the content of a SlugField.

And this will be our first admin site customization.

In the file myapp/admin.py add the prepopulated_fields attribute to CategoryAdmin and ProductAdmin classes:

class CategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}  # new
    list_display = ('name', 'slug', 'is_active', 'id',)


admin.site.register(Category, CategoryAdmin)


class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}  # new
    list_display = ('name', 'slug', 'is_active', 'id',)


admin.site.register(Product, ProductAdmin)

The prepopulated_fields attribute will make the Django admin site fill the slug field with what you type into the product or category name field during the creation of the record. It will not be changing the slug's value during the editing process though, because changing slugs is usually undesired behavior because it changes URLs.

Now when adding a category, I only had to type the category's name, and the slug field is automatically filled with the appropriate slug.

image

I have created four categories, and the change list looks like this: image