django/django
Management commands
django/core/management/ is the home of the django-admin and manage.py tooling. Every CLI subcommand — runserver, migrate, makemigrations, shell, test, dumpdata, loaddata, createsuperuser, etc. — is a BaseCommand subclass under django/core/management/commands/.
Purpose
Expose framework operations as a command-line tool. The runner discovers commands from django.core.management.commands and from each installed app's management/commands/ directory; the BaseCommand API standardises argument parsing, output formatting, and execution semantics (no-color, traceback handling, settings activation).
Directory layout
django/core/management/
├── __init__.py # execute_from_command_line, ManagementUtility
├── base.py # BaseCommand, AppCommand, LabelCommand
├── color.py # color_style, no_style, supports_color
├── sql.py # sql_flush helpers
├── templates.py # the startproject/startapp template engine
├── utils.py # find_command, popen_wrapper
└── commands/
├── runserver.py
├── migrate.py
├── makemigrations.py
├── makemessages.py
├── compilemessages.py
├── shell.py
├── test.py
├── testserver.py
├── startapp.py
├── startproject.py
├── createcachetable.py
├── dumpdata.py
├── loaddata.py
├── flush.py
├── inspectdb.py
├── diffsettings.py
├── showmigrations.py
├── squashmigrations.py
├── optimizemigration.py
├── sqlflush.py
├── sqlmigrate.py
├── sqlsequencereset.py
├── check.py
├── sendtestemail.py
└── dbshell.pyKey abstractions
| Type | File | Role |
|---|---|---|
BaseCommand |
base.py |
Base class for all commands |
AppCommand |
base.py |
BaseCommand that takes one or more app_labels |
LabelCommand |
base.py |
BaseCommand that takes one or more arbitrary labels |
CommandError, CommandParser, SystemCheckError |
base.py |
Standard errors and argparse subclass |
ManagementUtility |
__init__.py |
The CLI dispatcher |
execute_from_command_line |
__init__.py |
The entry point used by manage.py and the django-admin script |
How it works
graph TD
Script["manage.py / django-admin"]
EntryPoint["execute_from_command_line(argv)"]
Util["ManagementUtility"]
Discover["find commands<br/>(core + INSTALLED_APPS)"]
Cmd["MyCommand(BaseCommand)"]
Run["cmd.run_from_argv(argv)"]
Parser["argparse parser<br/>(populated by add_arguments)"]
Handle["cmd.handle(*args, **opts)"]
Script --> EntryPoint
EntryPoint --> Util
Util --> Discover
Discover --> Cmd
Cmd --> Run
Run --> Parser
Parser --> HandleDiscovery
get_commands() (in __init__.py) returns a dict mapping command names to the app label that provides them. The lookup walks:
django.core.management.commands(always present).- Each installed app's
<app>/management/commands/directory.
Apps later in INSTALLED_APPS override earlier ones for the same command name — that's how staticfiles overrides runserver to add its --insecure flag and static-file serving.
BaseCommand lifecycle
add_arguments(parser)— populate the argparse parser. Called byBaseCommand.run_from_argv.execute(\*args, **options)— parses arguments, configures color/no-color, and dispatches tohandle.handle(\*args, **options)— the user-implemented method. Returns a string (printed) or raisesCommandError.requires_system_checks— list of check tags to run before the command. Default:["__all__"]. Set to[]for commands that should run before settings are valid (e.g.,startproject).requires_migrations_checks— warn if migrations are outstanding.
BaseCommand.style is a color helper (self.stdout.write(self.style.SUCCESS("Done"))).
Settings activation
execute_from_command_line calls settings.configure() if no DJANGO_SETTINGS_MODULE is set and a settings file isn't required (e.g., startproject). For most commands it expects settings to be configured already — manage.py handles this by setting DJANGO_SETTINGS_MODULE before importing.
Notable commands
runserver
commands/runserver.py (~7 KB) is the dev server. It:
- Parses the address/port (default
127.0.0.1:8000). - Calls
django.core.servers.basehttp.run(a thin wrapper aroundwsgiref.simple_server.WSGIServer). - Wraps the handler chain with
StaticFilesHandlerifstaticfilesis inINSTALLED_APPS(overridden bycontrib/staticfiles/management/commands/runserver.py). - Uses
django.utils.autoreload.run_with_reloaderto spawn a child process and restart on file change.
The reloader is what makes runserver slow to start — it has to walk every importable module to set up file watches.
migrate and makemigrations
migrate.py (~21 KB) is the executor's front-end. It:
- Resolves the target (
app_label,migration_name, or implicit "everything"). - Calls
MigrationExecutor.migration_planto get the apply/unapply plan. - Runs the plan inside a transaction (where supported).
- Emits
pre_migrate/post_migratesignals.
makemigrations.py (~22 KB) is the autodetector's front-end. It:
- Resolves the target apps.
- Runs
MigrationAutodetector.changes()against current model state vs migration history. - Writes new migration files via
MigrationWriter. - Asks the user (via
MigrationQuestioner) for ambiguous decisions like field renames.
test
commands/test.py is a thin wrapper around django.test.utils.get_runner and the configured TEST_RUNNER (default: django.test.runner.DiscoverRunner). The runner does the heavy lifting; the command just parses CLI flags and dispatches.
shell
commands/shell.py opens an IPython, bpython, or stdlib code.interact REPL with django.setup() already called. The shell -c "<expr>" flag evaluates a single expression. The --interface flag picks between IPython, bpython, and Python.
inspectdb
Reverse-engineers a database into model definitions. Walks the database introspection API (connection.introspection.get_table_list(), get_table_description(), get_relations()) and emits a models.py-shaped string.
dumpdata / loaddata
Fixtures. dumpdata serialises model rows to JSON (or YAML/XML via django/core/serializers/). loaddata does the reverse, reading from <app>/fixtures/ or paths.
startproject / startapp
templates.py is the most interesting non-command in the directory. It implements the startproject and startapp template engine: copy a template directory, apply variable substitution (using a stripped-down version of the Django template language), rename files, and adjust permissions.
The default project template is at django/conf/project_template/. The default app template is at django/conf/app_template/. Custom templates can be supplied via --template <path-or-URL>; startproject https://example.com/template.tar.gz works.
check
commands/check.py runs the system check framework (see core utilities). It accepts tags (--tag models, --tag templates) and deployment-only checks (--deploy).
Integration points
- Settings —
execute_from_command_linereadsDJANGO_SETTINGS_MODULE. - Apps registry —
django.setup()runs before most commands; commands lookup uses the registry. - System checks — most commands run checks via
BaseCommand.execute. - Migrations —
makemigrations,migrate,showmigrations,sqlmigrate,optimizemigration,squashmigrationsall delegate to the migrations subsystem. - i18n —
makemessages,compilemessagesinvokegettexttooling.
Entry points for modification
- New core command: add a file in
django/core/management/commands/<name>.pywith aCommand(BaseCommand)class. - App-provided command: same shape, but inside
<app>/management/commands/. - Custom argument types: argparse handles this; use
parser.add_argument(..., type=...). - Override a built-in command: define the same name in your app's
management/commands/. Order inINSTALLED_APPSdecides who wins.
Key source files
| File | Purpose |
|---|---|
django/core/management/__init__.py |
ManagementUtility, execute_from_command_line |
django/core/management/base.py |
BaseCommand, AppCommand, LabelCommand (~25 KB) |
django/core/management/templates.py |
Project/app scaffolding |
django/core/management/color.py |
ANSI color support |
django/core/management/commands/runserver.py |
Dev server |
django/core/management/commands/migrate.py |
Apply migrations |
django/core/management/commands/makemigrations.py |
Generate migrations |
django/core/management/commands/test.py |
Test runner |
django/core/management/commands/shell.py |
REPL |
django/core/management/commands/inspectdb.py |
Reverse-engineer models |
django/core/management/commands/dumpdata.py |
Serialise data to fixtures |
django/core/management/commands/loaddata.py |
Load fixtures |
django/core/management/commands/startproject.py |
Project scaffolding |
django/core/management/commands/startapp.py |
App scaffolding |
Where to read tests
tests/admin_scripts/—manage.py/django-adminintegration tests.tests/runtests.py— used bymanage.py testindirectly.tests/migrations/test_commands.py—migrate/makemigrations/squashmigrations.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.