Contents
Django Admin in 10 Minutes: A Super Admin When You Need It NOW
“Friday, 4 p.m. Manager: I need an admin panel by Monday!” 😰
Don't panic. Django Admin is your rescuer.
Why Django Admin?
Django Admin is a fully functional admin panel included with Django: no frontend code, production ready, set up in ten minutes. It provides CRUD for models, search, filters and permissions.
Setup: a ten-minute quick start
Step 1: Installation (one minute)
# Virtual environment
python -m venv venv
# Activate (Linux/Mac)
source venv/bin/activate
# Activate (Windows)
venv\Scripts\activate
# Install Django
pip install django
# Verify
django-admin --version
# Output: 5.0.xStep 2: Create the project (two minutes)
# Create a Django project
django-admin startproject myadmin
# Structure:
# myadmin/
# manage.py <- Django CLI
# myadmin/
# __init__.py
# settings.py <- Configuration
# urls.py <- Routes
# wsgi.py <- Production server
cd myadmin
# Test run
python manage.py runserver
# Browser: http://127.0.0.1:8000/
# You will see: "The install worked successfully!" 🎉Step 3: Database setup (one minute)
# Django uses SQLite by default
# Perfect for a quick start!
# Migrate built-in tables
python manage.py migrate
# Output:
# Operations to perform:
# Apply all migrations: admin, auth, contenttypes, sessions
# Running migrations:
# Applying contenttypes.0001_initial... OK
# Applying auth.0001_initial... OK
# Applying admin.0001_initial... OK
# Applying sessions.0001_initial... OK
# Database created: db.sqlite3 ✅Step 4: Create a superuser (one minute)
# Create superuser account
python manage.py createsuperuser
# Interactive prompt:
Username: admin
Email: admin@example.com
Password: ********
Password (again): ********
# Output: Superuser created successfully. ✅Step 5: Start the admin panel (one minute)
# Start server
python manage.py runserver
# Open browser
# http://127.0.0.1:8000/admin/
# Login screen:
# Username: admin
# Password: (tvoje heslo)
# 🎉 VOILÀ! YOU HAVE AN ADMIN PANEL! 🎉You will see:
Django administration
─────────────────────
Authentication and Authorization
Groups
Users
Site administrationTotal time: six minutes! You now have user and group management, sessions, login/logout and password reset. Want custom models? Let's continue.
Custom models: four more minutes
Step 6: Create a Django app (one minute)
# Create app for your models
python manage.py startapp products
# Structure:
# products/
# __init__.py
# admin.py <- Admin registration (important!)
# apps.py
# models.py <- Model definitions (important!)
# views.py
# tests.py
# migrations/ <- Auto-generatedAdd to settings.py:
# myadmin/settings.py
INSTALLED_APPS = [
'django.contrib.admin', # Admin site
'django.contrib.auth', # Authentication
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products', # <- ADD THIS! Your app
]Step 7: Define models (two minutes)
# products/models.py
from django.db import models
class Category(models.Model):
"""Product category"""
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
ordering = ['name']
def __str__(self):
return self.name
class Product(models.Model):
"""Product model"""
STATUS_CHOICES = [
('draft', 'Draft'),
('active', 'Active'),
('archived', 'Archived'),
]
# Basic info
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
# Pricing
price = models.DecimalField(max_digits=10, decimal_places=2)
discount_price = models.DecimalField(
max_digits=10,
decimal_places=2,
null=True,
blank=True
)
# Inventory
stock = models.IntegerField(default=0)
sku = models.CharField(max_length=50, unique=True)
# Relations
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
related_name='products'
)
# Status
status = models.CharField(
max_length=10,
choices=STATUS_CHOICES,
default='draft'
)
featured = models.BooleanField(default=False)
# Timestamps
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
verbose_name = 'Product'
verbose_name_plural = 'Products'
def __str__(self):
return self.name
@property
def effective_price(self):
"""Return discount price if set, otherwise regular price"""
return self.discount_price if self.discount_price else self.priceStep 8: Register them in admin (one minute)
# products/admin.py
from django.contrib import admin
from .models import Category, Product
# BASIC REGISTRATION
# (This alone is enough to get started!)
admin.site.register(Category)
admin.site.register(Product)
# That's it! Django generates admin automatically! 🎉Step 9: Migrate the database (one minute)
# Create migrations
python manage.py makemigrations
# Output:
# Migrations for 'products':
# products/migrations/0001_initial.py
# - Create model Category
# - Create model Product
# Apply migrations
python manage.py migrate
# Output:
# Operations to perform:
# Apply all migrations: admin, auth, contenttypes, products, sessions
# Running migrations:
# Applying products.0001_initial... OK
# Database updated! ✅Step 10: Enjoy admin (zero minutes: refresh)
# The server is already running; refresh the browser
# http://127.0.0.1:8000/admin/
# Now you will see:
# ───────────────────
# PRODUCTS
# Categories [Add] [Change]
# Products [Add] [Change]
# ───────────────────
# Click "Add" pri Products
# Fill in the form generated by Django
# Click "Save"
# 🎉 You have CRUD for your models! 🎉Total: ten minutes from the start!
Advanced admin: level up
You have a working admin. Let's improve it.
Level 1: Better display
# products/admin.py
from django.contrib import admin
from .models import Category, Product
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
# Columns to display in list view
list_display = ['name', 'slug', 'product_count']
# Enable search
search_fields = ['name', 'description']
# Auto-generate slug from name
prepopulated_fields = {'slug': ('name',)}
# Custom column
def product_count(self, obj):
return obj.products.count()
product_count.short_description = 'Products'
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
# Columns in list view
list_display = [
'name',
'category',
'price',
'stock',
'status',
'featured',
'created_at'
]
# Filters in sidebar
list_filter = [
'status',
'featured',
'category',
'created_at'
]
# Search
search_fields = ['name', 'description', 'sku']
# Editable in list view (without opening detail)
list_editable = ['price', 'stock', 'status', 'featured']
# Default ordering
ordering = ['-created_at']
# Readonly fields
readonly_fields = ['created_at', 'updated_at', 'effective_price']
# Auto-generate slug
prepopulated_fields = {'slug': ('name',)}
# Organize fields in sections
fieldsets = (
('Basic Information', {
'fields': ('name', 'slug', 'description', 'category')
}),
('Pricing', {
'fields': ('price', 'discount_price', 'effective_price')
}),
('Inventory', {
'fields': ('stock', 'sku')
}),
('Status', {
'fields': ('status', 'featured')
}),
('Timestamps', {
'fields': ('created_at', 'updated_at'),
'classes': ('collapse',) # Collapsed by default
}),
)
# Now you have a PROFESSIONAL admin! 💼Refresh to see better columns, status/category/date filters, search, editable list fields and organized sections.
Level 2: Inline editing
# products/admin.py
from django.contrib import admin
from .models import Category, Product
class ProductInline(admin.TabularInline):
"""Edit products directly in category"""
model = Product
extra = 1 # How many empty forms
fields = ['name', 'price', 'stock', 'status']
show_change_link = True # Link to full edit
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'product_count']
search_fields = ['name']
prepopulated_fields = {'slug': ('name',)}
inlines = [ProductInline] # Add inline!
def product_count(self, obj):
return obj.products.count()
product_count.short_description = 'Products'
# Now when editing a category:
# You see all its products!
# You can edit them inline!
# 🎉Level 3: Custom actions
# products/admin.py
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'price', 'stock', 'status']
list_filter = ['status']
actions = [
'make_active',
'make_draft',
'apply_10_percent_discount',
'clear_discount'
]
def make_active(self, request, queryset):
"""Activate selected products"""
count = queryset.update(status='active')
self.message_user(
request,
f'{count} products activated.'
)
make_active.short_description = 'Activate selected products'
def make_draft(self, request, queryset):
"""Move to draft"""
count = queryset.update(status='draft')
self.message_user(
request,
f'{count} products moved to draft.'
)
make_draft.short_description = 'Move to draft'
def apply_10_percent_discount(self, request, queryset):
"""Apply 10% discount"""
for product in queryset:
product.discount_price = product.price * 0.9
product.save()
self.message_user(
request,
f'{queryset.count()} products discounted by 10%.'
)
apply_10_percent_discount.short_description = 'Apply 10% discount'
def clear_discount(self, request, queryset):
"""Remove discount"""
count = queryset.update(discount_price=None)
self.message_user(
request,
f'{count} discounts cleared.'
)
clear_discount.short_description = 'Clear discount'
# Usage:
# 1. Select products (checkboxes)
# 2. Choose action from dropdown
# 3. Click "Go"
# 4. Done! Batch operations! 🚀Level 4: Custom filters
# products/admin.py
from django.contrib import admin
class LowStockFilter(admin.SimpleListFilter):
title = 'stock level'
parameter_name = 'stock'
def lookups(self, request, model_admin):
return (
('low', 'Low stock (< 10)'),
('medium', 'Medium stock (10-50)'),
('high', 'High stock (> 50)'),
('out', 'Out of stock'),
)
def queryset(self, request, queryset):
if self.value() == 'low':
return queryset.filter(stock__lt=10, stock__gt=0)
if self.value() == 'medium':
return queryset.filter(stock__gte=10, stock__lte=50)
if self.value() == 'high':
return queryset.filter(stock__gt=50)
if self.value() == 'out':
return queryset.filter(stock=0)
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'price', 'stock', 'status']
list_filter = [
'status',
'featured',
'category',
LowStockFilter, # Custom filter!
]
# Now you have smart filters! 🎯Level 5: Image upload
# Install Pillow first
# pip install Pillow
# products/models.py
class Product(models.Model):
# ... existing fields ...
image = models.ImageField(
upload_to='products/',
blank=True,
null=True
)
# products/admin.py
from django.utils.html import format_html
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['image_preview', 'name', 'price', 'stock']
readonly_fields = ['image_preview']
def image_preview(self, obj):
if obj.image:
return format_html(
'<img src="{}" style="max-height: 50px;" />',
obj.image.url
)
return '-'
image_preview.short_description = 'Preview'
# settings.py - add media files config
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# urls.py - serve media in development
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Now you can upload images! 📸
# They show as thumbnails in admin!Customization: branding
# myadmin/urls.py
from django.contrib import admin
admin.site.site_header = "My Company Admin"
admin.site.site_title = "My Company Admin Portal"
admin.site.index_title = "Welcome to My Company Administration"
# Refresh admin - custom branding! 🎨Production deployment
# 1. Install production server
pip install gunicorn
# 2. Update settings.py
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
# Security settings
SECRET_KEY = 'your-secret-key-from-env'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
# 3. Collect static files
python manage.py collectstatic
# 4. Run with gunicorn
gunicorn myadmin.wsgi:application
# 5. Setup nginx (optional but recommended)
# Done! Production admin! 🚀Real-world tips
Tip 1: Permissions
# Give client LIMITED access
# Create group "Client Staff"
# Permissions:
# products | category | Can add category
# products | category | Can change category
# products | category | Can view category
# products | product | Can add product
# products | product | Can change product
# products | product | Can view product
#
# NO delete permissions!
# NO access to Users/Groups!
# Create user for client
# Add to "Client Staff" group
# They only see Products section! ✅Tip 2: Export data
# products/admin.py
from django.http import HttpResponse
import csv
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
actions = ['export_as_csv']
def export_as_csv(self, request, queryset):
meta = self.model._meta
field_names = [field.name for field in meta.fields]
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=products.csv'
writer = csv.writer(response)
writer.writerow(field_names)
for obj in queryset:
writer.writerow([getattr(obj, field) for field in field_names])
return response
export_as_csv.short_description = 'Export selected as CSV'
# Select products → Export as CSV → Download! 📥Tip 3: Import data
# products/admin.py
from django import forms
from django.shortcuts import render, redirect
import csv
class CsvImportForm(forms.Form):
csv_file = forms.FileField()
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
change_list_template = 'admin/products_changelist.html'
def get_urls(self):
from django.urls import path
urls = super().get_urls()
my_urls = [
path('import-csv/', self.import_csv),
]
return my_urls + urls
def import_csv(self, request):
if request.method == "POST":
csv_file = request.FILES["csv_file"]
decoded_file = csv_file.read().decode('utf-8').splitlines()
reader = csv.DictReader(decoded_file)
for row in reader:
Product.objects.create(
name=row['name'],
price=row['price'],
# ... other fields
)
self.message_user(request, "CSV import successful")
return redirect("..")
form = CsvImportForm()
return render(request, "admin/csv_form.html", {"form": form})
# Upload CSV → Products imported! 📤Conclusion
Django Admin is excellent for quick admin solutions, giving clients database access without SQL, content management, internal tools and MVP/prototype administration.
Ten-minute setup. Production ready. No frontend code. When a manager calls at 4 p.m. Friday, Django Admin can save the day! 🦸
Written by a developer who saved many Fridays with Django Admin. Sometimes the best solution is the fastest one. 😊