🏰 Django Advanced Admin: Your Magic Control Room
Imagine you’re the boss of a huge toy factory. You have a special control room where you can do amazing things — move toys around, change how things look, and make special buttons that do cool stuff. That’s exactly what Django’s Advanced Admin is!
🎯 The Big Picture
Django Admin is like a super-powered control panel for your website’s data. Today, we’re learning the advanced tricks — the ones that make you feel like a wizard! 🧙♂️
graph TD A["🏰 Django Admin"] --> B["⚡ Admin Actions"] A --> C["🎨 Custom Actions"] A --> D["📦 Inline Classes"] A --> E["✨ Site Customization"] style A fill:#667eea,color:#fff style B fill:#4ECDC4,color:#fff style C fill:#FF6B6B,color:#fff style D fill:#45B7D1,color:#fff style E fill:#96CEB4,color:#fff
⚡ Admin Actions: Magic Buttons for Many Things
What Are Admin Actions?
Think of Admin Actions like a TV remote with special buttons. Instead of changing channels one by one, you press ONE button and it does something to MANY things at once!
Real Example: You have 100 blog posts. Some are “draft” and you want to make 50 of them “published” at once. Without actions, you’d click each one — 50 times! 😫 With actions, you select them all, press ONE button, and DONE! ✨
Django’s Built-in Action
Django already gives you one action for free:
# This comes FREE with Django!
# It's the "Delete selected" action
# Select items → Action dropdown → Delete
When you check boxes next to items and pick “Delete selected items” — that’s an admin action working!
How Actions Work
- Select — Check the boxes next to items you want
- Choose — Pick an action from the dropdown menu
- Go! — Click the button and magic happens to ALL selected items
🎨 Custom Admin Actions: Build Your Own Magic Buttons
Why Make Your Own?
The “Delete” button is nice, but what if you want buttons like:
- ✅ “Mark as Published”
- ⭐ “Make Featured”
- 📧 “Send Email to Authors”
- 🏷️ “Add Discount”
You can build these yourself!
Your First Custom Action
Let’s make a “Publish” button for blog posts:
# In your admin.py file
# Step 1: Create the action function
@admin.action(
description="📢 Publish selected posts"
)
def make_published(modeladmin, request, queryset):
# queryset = all the items you selected
queryset.update(status='published')
# Step 2: Tell Admin to use it
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'status']
actions = [make_published]
What happens:
- You select 10 posts ☑️
- Choose “Publish selected posts” from dropdown
- Click “Go” → All 10 posts become published!
Understanding the Three Magic Ingredients
Every action function gets three things:
def my_action(modeladmin, request, queryset):
# modeladmin = the admin page itself
# request = info about who clicked
# queryset = the items you selected
Think of it like this:
- modeladmin = The kitchen (where you work)
- request = The waiter (who asked for food)
- queryset = The ingredients (items to cook)
More Cool Examples
Example 1: Mark items as featured
@admin.action(description="⭐ Mark as featured")
def make_featured(modeladmin, request, queryset):
queryset.update(is_featured=True)
Example 2: Give feedback message
from django.contrib import messages
@admin.action(description="✅ Approve selected")
def approve_items(modeladmin, request, queryset):
count = queryset.update(approved=True)
messages.success(
request,
f"Approved {count} items!"
)
Example 3: Send to specific users
@admin.action(description="📧 Notify authors")
def notify_authors(modeladmin, request, queryset):
for item in queryset:
send_email(item.author.email)
messages.info(
request,
"Emails sent successfully!"
)
📦 Admin Inline Classes: Show Related Stuff Together
The Problem Without Inlines
Imagine you have:
- Authors (people who write books)
- Books (written by authors)
Without inlines, to add books for an author:
- Go to Authors page → Edit author
- Go to Books page → Add book → Pick author
- Go back to Books → Add another book → Pick same author
- Back and forth, back and forth… 😵
The Magic of Inlines
With inlines, when you edit an Author, you see their Books right there on the same page! Add, edit, delete — all without leaving!
graph TD A["📝 Author Edit Page"] --> B["Author Name: J.K. Rowling"] A --> C["Author Email: jk@magic.com"] A --> D["📚 BOOKS INLINE"] D --> E["Book 1: Harry Potter 1"] D --> F["Book 2: Harry Potter 2"] D --> G["+ Add another book"] style A fill:#667eea,color:#fff style D fill:#4ECDC4,color:#fff
Two Types of Inlines
1. TabularInline — Like a spreadsheet (side by side)
class BookInline(admin.TabularInline):
model = Book
extra = 1 # Show 1 empty row for new book
2. StackedInline — Like stacked cards (one below another)
class BookInline(admin.StackedInline):
model = Book
extra = 1
Complete Inline Example
# models.py
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
class Book(models.Model):
author = models.ForeignKey(
Author,
on_delete=models.CASCADE
)
title = models.CharField(max_length=200)
published = models.DateField()
# admin.py
class BookInline(admin.TabularInline):
model = Book
extra = 2 # Show 2 empty rows
fields = ['title', 'published']
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ['name', 'email']
inlines = [BookInline] # Magic line!
Inline Options You Can Use
class BookInline(admin.TabularInline):
model = Book
extra = 1 # Empty forms to show
min_num = 0 # Minimum required
max_num = 10 # Maximum allowed
# Which fields to show
fields = ['title', 'published']
# Make some fields read-only
readonly_fields = ['created_at']
# Can users delete inline items?
can_delete = True
✨ Admin Site Customization: Make It YOURS!
Why Customize?
The default admin looks… default. 😴 But you can make it:
- Show your company logo
- Change colors
- Have a custom title
- Feel like YOUR app, not just “Django Admin”
Quick Customizations (In admin.py)
Change the header and title:
# At the top of admin.py
admin.site.site_header = "🚀 My Awesome Admin"
admin.site.site_title = "My App Admin"
admin.site.index_title = "Welcome to Control Panel"
Before: “Django administration” After: “🚀 My Awesome Admin” ✨
Create a Custom Admin Site
For bigger changes, create your own admin site:
# admin.py
from django.contrib.admin import AdminSite
class MyAdminSite(AdminSite):
site_header = "🎮 Game Control Center"
site_title = "Game Admin"
index_title = "Manage Your Games"
# Custom login message
login_template = 'admin/custom_login.html'
# Create instance
my_admin = MyAdminSite(name='myadmin')
# Register your models with YOUR site
my_admin.register(Game, GameAdmin)
my_admin.register(Player, PlayerAdmin)
In urls.py:
from .admin import my_admin
urlpatterns = [
path('my-admin/', my_admin.urls),
# Keep original too if needed:
path('admin/', admin.site.urls),
]
Customize Model Admin Display
Make your list views beautiful:
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
# Columns to show in list
list_display = [
'name',
'price',
'colored_status',
'in_stock'
]
# Add filters on the side
list_filter = ['category', 'in_stock']
# Search box
search_fields = ['name', 'description']
# Click column to edit
list_editable = ['price']
# Custom colored status!
@admin.display(description='Status')
def colored_status(self, obj):
color = 'green' if obj.active else 'red'
return format_html(
'<span style="color:{};">{}</span>',
color,
'Active' if obj.active else 'Inactive'
)
Organize Fields in Edit Form
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
fieldsets = [
('📝 Basic Info', {
'fields': ['title', 'slug']
}),
('📄 Content', {
'fields': ['body', 'summary'],
'classes': ['wide'] # Full width
}),
('⚙️ Settings', {
'fields': ['status', 'published_at'],
'classes': ['collapse'] # Collapsed!
}),
]
Custom Admin Templates
Override Django’s admin templates:
your_app/
├── templates/
│ └── admin/
│ ├── base_site.html # Main layout
│ └── your_app/
│ └── model/
│ └── change_list.html
base_site.html example:
{% extends "admin/base.html" %}
{% block branding %}
<h1 id="site-name">
<img src="/static/logo.png" height="40">
My Awesome Admin
</h1>
{% endblock %}
🎯 Putting It All Together
Here’s a complete example with everything:
from django.contrib import admin
from django.utils.html import format_html
from .models import Store, Product
# Custom Action
@admin.action(description="🏷️ Apply 10% discount")
def apply_discount(modeladmin, request, queryset):
for product in queryset:
product.price *= 0.9
product.save()
# Inline for Products
class ProductInline(admin.TabularInline):
model = Product
extra = 1
fields = ['name', 'price', 'in_stock']
# Main Admin
@admin.register(Store)
class StoreAdmin(admin.ModelAdmin):
list_display = ['name', 'location', 'product_count']
inlines = [ProductInline]
actions = [apply_discount]
@admin.display(description='Products')
def product_count(self, obj):
count = obj.product_set.count()
return format_html(
'<b>{}</b> items',
count
)
# Customize site
admin.site.site_header = "🏪 Store Manager"
admin.site.site_title = "Store Admin"
🌟 Key Takeaways
| Feature | What It Does | Like… |
|---|---|---|
| Admin Actions | Do something to many items at once | TV remote “ALL OFF” button |
| Custom Actions | Your own special buttons | Building your own remote |
| TabularInline | Related items as a table | Spreadsheet rows |
| StackedInline | Related items stacked vertically | Stacked cards |
| Site Customization | Change look & feel | Decorating your room |
🚀 You Did It!
You’ve learned Django Admin superpowers:
- ⚡ Make actions that affect many items at once
- 🎨 Create your own custom action buttons
- 📦 Show related items together with inlines
- ✨ Customize how your admin looks and feels
Now your admin panel isn’t just “a Django admin” — it’s YOUR admin, tailored to your needs! Go build something amazing! 🎉
