Obsah článku / Contents
Django Admin Panel za 10 minút: Super admin keď ho potrebuješ TERAZ

Django Admin Panel za 10 minút: Super admin keď ho potrebuješ TERAZ

"Piatok 16:00. Manager: Potrebujem admin panel do pondelka!" 😰

Nepanikár. Django Admin je tvoj zachránca.

Prečo Django Admin?

Django Admin je plne funkčný admin panel, ktorý dostaneš zadarmo s Djangom. Zero frontend code, production ready, setup za 10 minút.

Django Admin features:

  • ✅ Plne funkčný admin panel
  • ✅ CRUD pre všetky modely
  • ✅ Search, filters, permissions
  • ✅ Production ready
  • ✅ Zero frontend code
  • ✅ Setup za 10 minút!

Poďme na to!


Setup: 10-minútový quick start

Krok 1: Inštalácia (1 minúta)

bash
# Virtual environment
python -m venv venv

# Aktivovať (Linux/Mac)
source venv/bin/activate

# Aktivovať (Windows)
venv\Scripts\activate

# Nainštalovať Django
pip install django

# Verify
django-admin --version
# Output: 5.0.x

Krok 2: Vytvoriť projekt (2 minúty)

bash
# Vytvoriť Django projekt
django-admin startproject myadmin

# Štruktúra:
# 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/
# Uvidíš: "The install worked successfully!" 🎉

Krok 3: Database setup (1 minúta)

bash
# Django používa SQLite by default
# Perfektné pre 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

# Databáza vytvorená: db.sqlite3 ✅

Krok 4: Vytvoriť super admina (1 minúta)

bash
# Create superuser account
python manage.py createsuperuser

# Interaktívny prompt:
Username: admin
Email: admin@example.com
Password: ********
Password (again): ********

# Output: Superuser created successfully. ✅

Krok 5: Spustiť admin panel! (1 minúta)

bash
# Start server
python manage.py runserver

# Open browser
# http://127.0.0.1:8000/admin/

# Login screen:
# Username: admin
# Password: (tvoje heslo)

# 🎉 VOILÀ! MÁTE ADMIN PANEL! 🎉

Uvidíš:

Django administration
─────────────────────
Authentication and Authorization
  Groups
  Users

Site administration

Total time: 6 minút!

Teraz máš funkčný admin s:

  • ✅ User management
  • ✅ Group permissions
  • ✅ Session management
  • ✅ Login/logout
  • ✅ Password reset

Ale chceš vlastné modely? Poďme na to!


Vlastné modely: Ďalších 4 minúty

Krok 6: Vytvoriť Django app (1 minúta)

bash
# Create app for your models
python manage.py startapp products

# Štruktúra:
# products/
#   __init__.py
#   admin.py      <- Admin registration (important!)
#   apps.py
#   models.py     <- Model definitions (important!)
#   views.py
#   tests.py
#   migrations/   <- Auto-generated

Pridať do settings.py:

python
# 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
]

Krok 7: Definovať modely (2 minúty)

python
# 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.price

Krok 8: Registrovať v admin (1 minúta)

python
# 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! 🎉

Krok 9: Migrovať databázu (1 minúta)

bash
# 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! ✅

Krok 10: Užívať admin! (0 minút, just refresh)

bash
# Server už beží, len refresh browser
# http://127.0.0.1:8000/admin/

# Teraz uvidíš:
# ───────────────────
# PRODUCTS
#   Categories    [Add] [Change]
#   Products      [Add] [Change]
# ───────────────────

# Click "Add" pri Products
# Vyplň formulár (Django vygeneroval!)
# Click "Save"

# 🎉 Máš CRUD pre tvoje modely! 🎉

Total time: 10 minút od začiatku!


Advanced Admin: Level Up!

Teraz máš funkčný admin. Ale môžeme ho vylepšiť!

Level 1: Better Display

python
# 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 admin a uvidíš:

  • ✅ Better columns
  • ✅ Filters (status, category, date)
  • ✅ Search box
  • ✅ Editable fields in list
  • ✅ Organized sections

Level 2: Inline Editing

python
# 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

python
# 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

python
# 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

python
# 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

python
# 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

bash
# 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

python
# 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

python
# 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

python
# 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! 📤

Záver

Django Admin je perfektný tool pre:

  • ✅ Rýchle admin riešenia (10 minút setup)
  • ✅ Dať klientom prístup do databázy bez SQL
  • ✅ Content management
  • ✅ Internal tools
  • ✅ MVP/prototype admin

Setup za 10 minút. Production ready. Zero frontend code.

Keď manager volá v piatok o 16:00, Django Admin je tvoj zachránca! 🦸


Tutorial napísal developer ktorý zachránil veľa piatkov pomocou Django Admin. Sometimes the best solution is the fastest one. 😊

Všetky články