Inlines, Uneditable Fields, and ModelAdmin Methods
Learn about inlines, read-only fields, and how to override ModelAdmin methods.
We'll cover the following
Using inlines
Now, you will focus on adding some functionalities to change_view
pages (page to create or edit a model instance). Sometimes, it can be useful when editing a model to see or add foreign key values too. For example, you could say that when editing an author, we would like to add or see his questions.
To do this, you will use the inlines
keyword:
class QuestionInline(admin.TabularInline):
model = Question
class AuthorAdmin(admin.ModelAdmin):
...
inlines = [QuestionInline,]
...
First, you need to define a new class QuestionInline
which inherits from admin.TabularInline
or admin.StackedInline,
and then, in your AuthorAdmin, you will specify the inlines class name with inlines=[QuestionInline,]
.
As a result, Django admin will display the existing questions for the selected author along with some new rows to add questions. This is the result of inheriting from TabularInline
:
Get hands-on with 1200+ tech skills courses.