[Answered ]-Django: Displaying only the text of a form in admin

2👍

Either in your ModelAdmin.formfield_overrides, or ModelAdmin.formfield_for_dbfield, or in a custom ModelForm, you need to assign a custom widget to the name_slug field that just displays the value of the field rather than displaying an HTML form input. You can find just such a widget here.

EDIT: I won’t get into the details of creating a custom widget, as you can just use the one I linked to above. To enable this widget for all SlugField’s in a model, the simplest way is to use formfield_overrides:

class PageAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.SlugField: {'widget': ReadOnlyWidget},
    }

If you have multiple SlugFields in your model and only want to apply the ReadOnlyWidget to one of them, you’d override the formfield_for_dbfield method:

class PageAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'name_slug':
            kwargs['widget'] = ReadOnlyWidget
        return super(PageAdmin, self).formfield_for_dbfield(db_field, **kwargs)

You can also create a fully-custom ModelForm for your model and assign it to the form attribute of your ModelAdmin, but that isn’t necessary unless you’re doing deeper customizations.

Leave a comment