Management Commands (Django)
Management commands are the subcommands you run with python manage.py, such as runserver, migrate, and createsuperuser. You can also write your own custom commands for tasks like data imports or scheduled jobs.
Django
manage.py is Django's command-line entry point, and each subcommand is a management command. Built-in ones cover the project lifecycle: runserver (dev server), makemigrations/migrate (schema), createsuperuser (admin account), shell (a Python shell with Django loaded), collectstatic, and test.
Custom commands let you run project code from the CLI or cron. You create one by adding a module under an app's management/commands/ folder that defines a Command class subclassing BaseCommand and implementing handle(). Then python manage.py mycommand runs it.
Custom commands are the right tool for one-off scripts and scheduled tasks (data backfills, sending digest emails, cleanup jobs) because they run inside the full Django environment with settings, the ORM, and apps all loaded.
Syntax
python manage.py <command>
class Command(BaseCommand): def handle(self): ...Examples
Python
# blog/management/commands/cleanup.py
from django.core.management.base import BaseCommand
from blog.models import Post
class Command(BaseCommand):
help = "Delete draft posts"
def handle(self, *args, **options):
n, _ = Post.objects.filter(published=False).delete()
self.stdout.write(f"Deleted {n} drafts")