ZetCode

Django management commands

last modified November 21, 2026 Python 3.15

Every task that we run with manage.py, such as migrate, runserver, or createsuperuser, is a management command. A project can add its own commands for the jobs that do not belong to a web request: importing data, sending a newsletter, cleaning up old records, or anything that a cron job should run. In this article we look at the built-in commands, write commands with arguments and options, report errors, import a CSV file in a transaction, call commands from Python code, save and load data with fixtures, and test the commands. The examples use Django 6.1 and Python 3.15.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app library, and create the folder demos for demo scripts.

$ mkdir commands
$ cd commands
$ uv init --bare
$ uv add django
$ uv run django-admin startproject config .
$ uv run python manage.py startapp library
$ mkdir demos

The trailing dot in startproject config . creates manage.py and the config package in the current directory instead of one level deeper. A new app is ignored by Django until it is listed in INSTALLED_APPS, so we add the app to the list in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'library',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

The app library has one model, a book with a unique title, an author, and an optional year of publication.

library/models.py
from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=100, unique=True)
    author = models.CharField(max_length=60)
    year = models.PositiveIntegerField(null=True, blank=True)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return f'{self.title} by {self.author}'

We create the migration and apply it.

$ uv run python manage.py makemigrations library
Migrations for 'library':
  library/migrations/0001_initial.py
    + Create model Book
$ uv run python manage.py migrate | tail -n 2
  Applying library.0001_initial... OK
  Applying sessions.0001_initial... OK

Built-in commands

Running manage.py help without arguments lists the available commands, grouped by the app that provides them. The group [django] holds the core commands; the apps auth, contenttypes, sessions, and staticfiles add their own. The command runserver is listed under staticfiles because that app overrides the core version to serve static files.

$ uv run python manage.py help

Type 'manage.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    optimizemigration
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

Some of the commands are covered in their own articles: makemigrations and migrate in Django migrations, collectstatic in Django static files, makemessages in Django internationalization, and test later in this article. The command check runs the system checks, which look for mistakes in the settings, models, and URLs, and version prints the version of Django.

$ uv run python manage.py check
System check identified no issues (0 silenced).
$ uv run python manage.py version
6.1.3

The first command

Django looks for commands in the package management/commands of every installed app. Each module in that package whose name does not start with an underscore is a command named after the module. Both directories need an __init__.py file, which can be empty.

$ tree library/management
library/management
├── commands
│   ├── countbooks.py
│   └── __init__.py
└── __init__.py

1 directory, 3 files

The module must define a class named Command that extends BaseCommand. The attribute help is the description shown by manage.py help, and the method handle() does the work. When it runs, Django is already set up, so the command can use the models directly.

library/management/commands/countbooks.py
from django.core.management.base import BaseCommand

from library.models import Book


class Command(BaseCommand):
    help = 'Prints the number of books in the library'

    def handle(self, *args, **options):
        count = Book.objects.count()
        self.stdout.write(f'The library has {count} books')

The command writes with self.stdout.write() instead of print(). The wrapper adds the newline, and the output can be redirected when the command is called from code or tests. The help of the command shows our description and the options that every command gets from BaseCommand: the verbosity, the settings module, the traceback of errors, and the colours. Before handle() runs, Django runs the system checks, which --skip-checks turns off.

$ uv run python manage.py countbooks
The library has 0 books
$ uv run python manage.py help countbooks
usage: manage.py countbooks [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                            [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                            [--skip-checks]

Prints the number of books in the library

options:
  -h, --help            show this help message and exit
  --version             Show program's version number and exit.
  -v, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output, 2=verbose output,
                        3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g. "myproject.settings.main". If
                        this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will
                        be used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Display a full stack trace on CommandError exceptions.
  --no-color            Don't colorize the command output.
  --force-color         Force colorization of the command output.
  --skip-checks         Skip system checks.

Arguments and errors

Commands parse their command line with argparse. The method add_arguments() receives the parser, and we add positional arguments and options with parser.add_argument(), exactly as in a standalone script. The parsed values arrive in the dictionary options of handle(), keyed by their names. The option --year is converted to an integer by type=int and is None when it is omitted.

library/management/commands/addbook.py
from django.core.management.base import BaseCommand, CommandError

from library.models import Book


class Command(BaseCommand):
    help = 'Adds a book to the library'

    def add_arguments(self, parser):
        parser.add_argument('title', help='title of the book')
        parser.add_argument('author', help='name of the author')
        parser.add_argument('--year', type=int, help='year of publication')

    def handle(self, *args, **options):
        title = options['title']
        if Book.objects.filter(title=title).exists():
            raise CommandError(f'The book {title!r} is already in the library')

        book = Book.objects.create(title=title, author=options['author'],
                                   year=options['year'])
        self.stdout.write(self.style.SUCCESS(f'Added {book}'))

The command refuses a title that already exists by raising CommandError. The attribute style has methods such as SUCCESS, WARNING, ERROR, and NOTICE that wrap a text in terminal colours. We add three books.

$ uv run python manage.py addbook 'The Hobbit' 'J. R. R. Tolkien' --year 1937
Added The Hobbit by J. R. R. Tolkien
$ uv run python manage.py addbook Dune 'Frank Herbert' --year 1965
Added Dune by Frank Herbert
$ uv run python manage.py addbook 'Children of Dune' 'Frank Herbert'
Added Children of Dune by Frank Herbert
$ uv run python manage.py countbooks
The library has 3 books

manage.py catches a CommandError, prints its message to the standard error, and exits with the status 1, so a shell script or a cron job can see that the command failed. A missing argument or a value that cannot be converted is reported by argparse with the usage line and the exit status 2.

$ uv run python manage.py addbook Dune 'Frank Herbert'; echo "exit status: $?"
CommandError: The book 'Dune' is already in the library
exit status: 1
$ uv run python manage.py addbook Dune --year 1965; echo "exit status: $?"
usage: manage.py addbook [-h] [--year YEAR] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                         [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                         [--skip-checks]
                         title author
manage.py addbook: error: the following arguments are required: author
exit status: 2
$ uv run python manage.py addbook Emma 'Jane Austen' --year soon; echo "exit status: $?"
usage: manage.py addbook [-h] [--year YEAR] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
                         [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                         [--skip-checks]
                         title author
manage.py addbook: error: argument --year: invalid int value: 'soon'
exit status: 2

The option --traceback prints the full stack trace of the CommandError instead of only its message, which helps when the reason for the error is not clear.

$ uv run python manage.py addbook Dune 'Frank Herbert' --traceback 2>&1 | tail -n 4
    output = self.handle(*args, **options)
  File "./library/management/commands/addbook.py", line 17, in handle
    raise CommandError(f'The book {title!r} is already in the library')
django.core.management.base.CommandError: The book 'Dune' is already in the library

Options, styles, and verbosity

The next command lists the books. The option --author has the short form -a; --format accepts only the values in choices; and --undated is a flag, which action='store_true' turns into a boolean. The dashes in option names become underscores in options.

library/management/commands/listbooks.py
import json

from django.core.management.base import BaseCommand

from library.models import Book


class Command(BaseCommand):
    help = 'Lists the books in the library'

    def add_arguments(self, parser):
        parser.add_argument('-a', '--author', help='show only books by this author')
        parser.add_argument('--format', choices=['text', 'json'], default='text')
        parser.add_argument('--undated', action='store_true',
                            help='show only books without a year')

    def handle(self, *args, **options):
        books = Book.objects.all()
        if options['author']:
            books = books.filter(author__icontains=options['author'])
        if options['undated']:
            books = books.filter(year__isnull=True)

        if options['format'] == 'json':
            data = list(books.values('title', 'author', 'year'))
            self.stdout.write(json.dumps(data, indent=2))
            return

        for book in books:
            year = book.year or self.style.WARNING('unknown')
            self.stdout.write(f'{book.title:<20} {book.author:<20} {year}')

        if options['verbosity'] >= 2:
            self.stderr.write(f'{len(books)} of {Book.objects.count()} books shown')

The JSON format is meant for other programs, so it contains only the data. The text format marks a missing year with the warning style. Every command has the option -v or --verbosity with the levels 0 to 3; the default is 1. Our command prints a summary at the level 2 and writes it to self.stderr, so that it does not mix with the data when the output is redirected to a file. An invalid choice is rejected by the parser.

$ uv run python manage.py listbooks
Children of Dune     Frank Herbert        unknown
Dune                 Frank Herbert        1965
The Hobbit           J. R. R. Tolkien     1937
$ uv run python manage.py listbooks -a herbert -v 2
Children of Dune     Frank Herbert        unknown
Dune                 Frank Herbert        1965
2 of 3 books shown
$ uv run python manage.py listbooks --undated --format json
[
  {
    "title": "Children of Dune",
    "author": "Frank Herbert",
    "year": null
  }
]
$ uv run python manage.py listbooks --format xml; echo "exit status: $?"
usage: manage.py listbooks [-h] [-a AUTHOR] [--format {text,json}] [--undated] [--version]
                           [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH]
                           [--traceback] [--no-color] [--force-color] [--skip-checks]
manage.py listbooks: error: argument --format: invalid choice: 'xml' (choose from 'text', 'json')
exit status: 2

Django adds the colours only when the output goes to a terminal. Piped through cat -v, which shows control characters, the output is plain; --force-color adds the escape sequences even to a pipe, and --no-color removes them on a terminal.

$ uv run python manage.py listbooks --undated | cat -v
Children of Dune     Frank Herbert        unknown
$ uv run python manage.py listbooks --undated --force-color | cat -v
Children of Dune     Frank Herbert        ^[[33;1munknown^[[0m

Importing a CSV file

A typical job for a command is a data import. The file books.csv has a header row and six books; one has no author and one has an invalid year.

books.csv
title,author,year
Dune,Frank Herbert,1965
Emma,Jane Austen,1815
Persuasion,Jane Austen,1817
The Road,Cormac McCarthy,2006
Nameless,,1999
Neuromancer,William Gibson,198x

The command reads the file with csv.DictReader and turns a missing or unreadable file into a CommandError. Rows with errors are reported as warnings on the standard error and skipped; the others are saved with update_or_create(), which updates a book with the same title and creates the rest.

library/management/commands/importbooks.py
import csv

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from library.models import Book


class Command(BaseCommand):
    help = 'Imports books from a CSV file with the columns title, author, and year'

    def add_arguments(self, parser):
        parser.add_argument('path', help='CSV file to import')
        parser.add_argument('--dry-run', action='store_true',
                            help='check the file and roll back all changes')

    @transaction.atomic
    def handle(self, *args, **options):
        try:
            with open(options['path'], newline='', encoding='utf-8') as f:
                rows = list(csv.DictReader(f))
        except OSError as e:
            raise CommandError(f'Cannot read {options["path"]}: {e.strerror}')

        created = updated = skipped = 0
        for line, row in enumerate(rows, start=2):
            year = row['year'].strip()
            if not row['author'].strip() or (year and not year.isdigit()):
                self.stderr.write(self.style.WARNING(f'line {line}: skipped {row}'))
                skipped += 1
                continue

            _, new = Book.objects.update_or_create(
                title=row['title'].strip(),
                defaults={'author': row['author'].strip(), 'year': int(year) if year else None},
            )
            if new:
                created += 1
            else:
                updated += 1

        if options['dry_run']:
            transaction.set_rollback(True)
            self.stdout.write('Dry run, nothing was saved')
        self.stdout.write(self.style.SUCCESS(
            f'{created} created, {updated} updated, {skipped} skipped'))

The decorator transaction.atomic on handle() runs the whole import in one transaction, so a crash in the middle leaves the database unchanged. The option --dry-run uses the same transaction to check a file: after the loop, transaction.set_rollback(True) marks the transaction to be rolled back instead of committed (see Django raw SQL and transactions). The dry run reports the same numbers as the real one but leaves three books in the library; the real run creates three books and updates Dune.

$ uv run python manage.py importbooks books.csv --dry-run
line 6: skipped {'title': 'Nameless', 'author': '', 'year': '1999'}
line 7: skipped {'title': 'Neuromancer', 'author': 'William Gibson', 'year': '198x'}
Dry run, nothing was saved
3 created, 1 updated, 2 skipped
$ uv run python manage.py countbooks
The library has 3 books
$ uv run python manage.py importbooks books.csv
line 6: skipped {'title': 'Nameless', 'author': '', 'year': '1999'}
line 7: skipped {'title': 'Neuromancer', 'author': 'William Gibson', 'year': '198x'}
3 created, 1 updated, 2 skipped
$ uv run python manage.py countbooks
The library has 6 books
$ uv run python manage.py importbooks missing.csv; echo "exit status: $?"
CommandError: Cannot read missing.csv: No such file or directory
exit status: 1

Calling commands from code

The function call_command() runs a command from Python code: from a view, a test, another command, or a script. Positional arguments are passed as strings, the same as on the command line, and options either as strings too or as keyword arguments named after the destination of the option, such as author or dry_run. The keyword arguments stdout and stderr redirect the output to any object with a write() method, typically StringIO.

demos/calls.py
import os
from io import StringIO

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.core.management import call_command
from django.core.management.base import CommandError

call_command('countbooks')

out = StringIO()
call_command('listbooks', author='austen', stdout=out)
print('captured:', out.getvalue().splitlines())

call_command('listbooks', '--author', 'herbert', '--format', 'json', stdout=out)
print('length of the captured text:', len(out.getvalue()))

try:
    call_command('addbook', 'Emma', 'Jane Austen')
except CommandError as e:
    print('CommandError:', e)

call_command('check', stdout=out)
print(out.getvalue().splitlines()[-1])

The first call prints to the console because no stdout was given. The second call captures the two books by Jane Austen; the third appends a JSON document to the same buffer. Unlike on the command line, call_command() lets a CommandError propagate, so the caller can handle it. The built-in commands are called the same way, here check. Before the demo runs, the help shows our four commands in the group [library].

$ uv run python manage.py help | grep -A 4 'library'
[library]
    addbook
    countbooks
    importbooks
    listbooks
$ uv run python -m demos.calls
The library has 6 books
captured: ['Emma                 Jane Austen          1815', 'Persuasion           Jane Austen          1817']
length of the captured text: 265
CommandError: The book 'Emma' is already in the library
System check identified no issues (0 silenced).

Fixtures with dumpdata and loaddata

Two built-in commands move data between the database and files. dumpdata serializes the objects of an app or a model to JSON, XML, or YAML, and loaddata loads such a file, called a fixture. Fixtures in the folder fixtures of an app can be loaded by their name. The option -o writes the data to a file, and --indent makes it readable.

$ mkdir -p library/fixtures
$ uv run python manage.py dumpdata library --indent 2 -o library/fixtures/books.json
$ head -n 18 library/fixtures/books.json
[
{
  "model": "library.book",
  "pk": 1,
  "fields": {
    "title": "The Hobbit",
    "author": "J. R. R. Tolkien",
    "year": 1937
  }
},
{
  "model": "library.book",
  "pk": 2,
  "fields": {
    "title": "Dune",
    "author": "Frank Herbert",
    "year": 1965
  }

Each object is stored with its model, primary key, and fields. The command flush deletes all data from the database, and loaddata brings the books back with the same primary keys; an object with an existing key is overwritten. Fixtures are handy for sample data and for tests.

$ uv run python manage.py flush --no-input
$ uv run python manage.py countbooks
The library has 0 books
$ uv run python manage.py loaddata books
Installed 6 object(s) from 1 fixture(s)
$ uv run python manage.py countbooks
The library has 6 books

Testing commands

Commands are tested with call_command(). The helper run() captures both output streams. The test case loads the fixture books, which we have just created, into the test database, and checks the output, the database, and the errors. The test of the dry run writes a temporary CSV file with one good and one bad row.

library/tests.py
import tempfile
from io import StringIO

from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase

from .models import Book


def run(*args, **options):
    out, err = StringIO(), StringIO()
    call_command(*args, stdout=out, stderr=err, **options)
    return out.getvalue(), err.getvalue()


class CommandTests(TestCase):
    fixtures = ['books']

    def test_countbooks(self):
        out, _ = run('countbooks')
        self.assertEqual(out, 'The library has 6 books\n')

    def test_addbook(self):
        out, _ = run('addbook', 'Ulysses', 'James Joyce', year=1922)
        self.assertIn('Added Ulysses by James Joyce', out)
        self.assertEqual(Book.objects.get(title='Ulysses').year, 1922)

    def test_addbook_refuses_a_duplicate(self):
        with self.assertRaisesMessage(CommandError, 'already in the library'):
            run('addbook', 'Dune', 'Frank Herbert')

    def test_listbooks_filters_by_author(self):
        out, _ = run('listbooks', author='austen', no_color=True)
        self.assertEqual(len(out.splitlines()), 2)

    def test_importbooks_dry_run_saves_nothing(self):
        with tempfile.NamedTemporaryFile('w', suffix='.csv') as f:
            f.write('title,author,year\nUlysses,James Joyce,1922\n,,x\n')
            f.flush()
            out, err = run('importbooks', f.name, dry_run=True)
        self.assertIn('1 created, 0 updated, 1 skipped', out)
        self.assertIn('line 3: skipped', err)
        self.assertFalse(Book.objects.filter(title='Ulysses').exists())

The option no_color=True makes the comparison independent of the terminal. Commands that run on a schedule can then be called from cron with the full path of the interpreter of the environment, for example 0 3 * * * cd /srv/library && .venv/bin/python manage.py importbooks /data/books.csv. All five tests pass.

$ uv run python manage.py test library 2>&1
Found 5 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 5 tests in 0.018s

OK
Destroying test database for alias 'default'...

Source

Django documentation: How to create custom django-admin commands

Django documentation: django-admin and manage.py

Python documentation: argparse

In this article we have used the built-in management commands, written custom commands with BaseCommand, parsed arguments and options, reported errors with CommandError, imported a CSV file in a transaction with a dry run, called commands with call_command(), saved and loaded fixtures, and tested the commands. Related articles are Django migrations, Django raw SQL and transactions, and Django settings and environment.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.