Let'sh
ModelAdmin Option

ModelAdmin Options

ModelAdmin allows us to create admin interface quickly and much flexibility (opens in a new tab).


list_display

list_display (opens in a new tab) determines which fields of models to show on the admin panel.

Let's say we have User model defined as below:

users/models.py
Copy

class User(models.Model):
email = models.EmailField()
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

users/admin.py
Copy

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ['email', 'first_name', 'last_name', 'is_active', 'is_admin']

Then it will display as below.

list_display

Or you can also include customized fields by using custom methods based on the fields information. Below example shows how to print the full name of user combining with his/her first_name and last_name and make them all uppercase.

users/admin.py
Copy

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
# ...
def upper_case_name(self, obj):
return f"{obj.first_name} {obj.last_name}".upper()

upper_case_name


list_filter

list_filter (opens in a new tab) reorgnizes the information displayed on list_display by certain condition that admin user chose.

For instance, we can rearrange the user data table based on is_active and is_admin as below.

users/admin.py
Copy

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_filter = ["is_active", "is_admin"]

list_filter

search_fields

search_fields (opens in a new tab) allows us to search fields on list_display with certain keywords.

users/admin.py
Copy

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
search_fields = ["email"]

Above example shows that admin user can search users by their email field. Of course, we can include multiple fields if we want to.

search_fields

By default, search_fields provides icontains (opens in a new tab) feature that searches all results containing certain keywords. However, we can also use startswith (opens in a new tab) feature by using ^ for searching words that starts only with that keyword.

For fields that are connected by ForeignKey or ManyToManyField, we can search results as below:


search_fields = ["foreign_key__related_fieldname"]