Customizing the Django Admin: list_display and search_fields

3D isometric illustration of a basic desk transforming into a high-tech dashboard with searchlights, representing Django Admin customization.

You’ve used admin.site.register(Post) to add your model to the admin. But the result is ugly: just a list of Post object (1), Post object (2), etc. If you want a more professional result, you’ll need to customise Django Admin to better display your models.

Let’s make it a powerful, searchable data dashboard in 5 minutes.

Step 1: Create a ModelAdmin Class

In your app’s admin.py (e.g., pages/admin.py), we need to create a special class to control the Post model’s settings.

# pages/admin.py
from django.contrib import admin
from .models import Post

# This is the new part!
class PostAdmin(admin.ModelAdmin):
    pass # We'll add settings here

# Register your model using the new class
admin.site.register(Post, PostAdmin)

Step 2: list_display (Show Useful Columns)

Let’s show the title and author instead of “Post object”.

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')

Just adding that one line changes your admin to show a beautiful table.

Step 3: search_fields (Add a Search Bar)

This adds a search bar that can search inside your text fields.

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')
    search_fields = ('title', 'text') # Search these two fields

Step 4: list_filter (Add a Filter Sidebar)

This adds a sidebar that lets you filter by dates, users, or other categories.

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')
    search_fields = ('title', 'text')
    list_filter = ('author', 'created_at') # Add filters

The Final Result

Your pages/admin.py should look like this:

from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')
    search_fields = ('title', 'text')
    list_filter = ('author', 'created_at')

admin.site.register(Post, PostAdmin)

With just 4 lines of code, your admin panel is now a professional, usable tool!


Key Takeaways

  • To achieve a better display of your model in Django Admin, create a custom ModelAdmin class.
  • Use the list_display option to show useful columns like title and author instead of generic object names.
  • Add a search bar with search_fields to allow searching within your text fields.
  • Incorporate list_filter to enable filtering by dates, users, or categories for better navigation.
  • With just four lines of code, you can significantly enhance the usability of your Django Admin interface.

Similar Posts

Leave a Reply