0
0
Djangoframework~5 mins

Admin customization with ModelAdmin in Django

Choose your learning style9 modes available
Introduction

ModelAdmin lets you change how your data shows up in Django's admin site. It helps you make the admin easier to use and look better.

You want to show only certain fields in the admin list view.
You want to add search boxes to find data quickly.
You want to filter data by categories or dates in the admin.
You want to change the order of fields when editing a record.
You want to add custom buttons or actions for your data.
Syntax
Django
from django.contrib import admin
from .models import YourModel

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('field1', 'field2')
    search_fields = ('field1',)
    list_filter = ('field3',)

admin.site.register(YourModel, YourModelAdmin)

list_display controls which fields show in the list view.

search_fields adds a search box for specified fields.

Examples
Shows only title and author columns in the book list.
Django
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
Adds a search box to find books by title or author name.
Django
class BookAdmin(admin.ModelAdmin):
    search_fields = ('title', 'author__name')
Adds a filter sidebar to filter books by publication year.
Django
class BookAdmin(admin.ModelAdmin):
    list_filter = ('publication_year',)
Sample Program

This code customizes the admin for the Book model. It shows title, author, and year in the list. It adds a search box for title and author name. It also adds a filter for publication year.

Django
from django.contrib import admin
from .models import Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'publication_year')
    search_fields = ('title', 'author__name')
    list_filter = ('publication_year',)

admin.site.register(Book, BookAdmin)
OutputSuccess
Important Notes

Remember to import your model and admin module correctly.

Use double underscores (__) to search or filter on related model fields.

After changes, restart the Django server to see updates in admin.

Summary

ModelAdmin lets you control how models appear in Django admin.

You can show specific fields, add search, and filters easily.

This makes managing data faster and clearer for admins.