Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 77 ยท Middleware, Signals and Internals

Custom Management Commands

Write your own manage.py commands with BaseCommand: add arguments and flags, print styled output, raise CommandError, test with call_command and schedule jobs.

Every Django developer runs commands like python manage.py migrate and python manage.py createsuperuser. These are management commands, and you can write your own. A custom command is the right home for code that should run from a terminal or a scheduler rather than from a web request: importing a CSV, deleting expired records, sending a nightly digest, rebuilding a cache or seeding demo data.

Writing a command instead of a loose script has real advantages. Django has already loaded your settings and models by the time it runs, you get argument parsing and help text for free, and the same function can be tested from Python with call_command. This lesson covers all of it. The live examples call commands directly in the browser, because there is no terminal here; the layout you use on your own machine is shown in a read-only snippet.

Where a command lives

A command is a class named Command, in a module whose file name is the command name. Django finds it by looking inside every installed app, in a package called management/commands:

TEXT
blog/
    management/
        __init__.py
        commands/
            __init__.py
            purge_drafts.py      <- run with: python manage.py purge_drafts

Both __init__.py files are required. The file name (without .py) is the command name, so use lowercase with underscores. Files that start with an underscore are ignored, which is handy for shared helpers.

Here is the smallest useful command, as it would appear in purge_drafts.py:

Python
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Delete draft posts older than the given number of days."

    def handle(self, *args, **options):
        self.stdout.write("Nothing to delete.")

handle() is where the work happens. help appears in python manage.py help purge_drafts.

Arguments and options

Override add_arguments() to declare arguments. It receives a standard argparse parser, so everything you know from Python's command-line programs applies. Whatever the user passes arrives in handle() as keyword arguments in options.

The next example is a command that greets people. It shows a positional argument, a numeric option, a boolean flag and the built-in output styles. Instead of locating the command by name, we pass an instance of it to call_command, which is the same function you would use in tests.

Python A command with arguments and styled output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the two ways of passing arguments to call_command. You can write them the way you would on the command line ("--shout", "--verbosity", "2"), or as Python keywords (times=2). Keywords use the argument's destination name, so --dry-run becomes dry_run=True.

Some details worth knowing:

  • Always write to self.stdout, not print(). Django lets callers redirect it (we passed a StringIO above), so tests can capture the output. Use self.stderr for errors.
  • self.style offers SUCCESS, WARNING, ERROR, NOTICE and a few more. When the output is a terminal they add colors; when it is redirected, as in our example, no color codes are added.
  • verbosity (0 to 3) and the other built-in flags like --settings and --no-color are added for you.
  • CommandError is the right way to fail. On the command line it prints the message without a traceback and exits with status 1. From call_command it is an ordinary exception you can catch.
  • If handle() returns a string, Django writes it to standard output for you.

A realistic command: clean up old records

Most commands touch the database. A good habit is to give destructive commands a --dry-run option that reports what would happen. The next example deletes expired sessions-style records older than a given number of days. To keep the output deterministic, the command accepts a reference date instead of calling "now" itself, a trick that also makes it easy to test.

flowchart LR
    C["cron or scheduler"] --> M["python manage.py<br/>purge_old_notes"]
    M --> H["Command.handle()"]
    H --> D[("Database")]
    H --> O["stdout / log"]

A scheduler runs the same management command you can run by hand; the command talks to the database through the ORM.

Python A cleanup command with --dry-run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the output step by step. The dry run reports two notes but removes nothing. The real run deletes the two oldest notes. The third call uses keyword arguments (days=10) with a stricter cutoff, so the 20-day-old note goes too. The last call is rejected by a validation check.

The same call_command("purge_old_notes", "--days", "30") call, written with the command's name, works inside a project and in tests, as long as the app is in INSTALLED_APPS.

Running commands on a schedule

Django does not include a scheduler. The usual options are:

  • cron (Linux and macOS): a line such as 0 3 * * * cd /srv/app && .venv/bin/python manage.py purge_old_notes --days 30 runs the command every night at 03:00.
  • systemd timers or your hosting platform's scheduled-jobs feature.
  • A task queue with periodic tasks (Celery beat, covered in Docker, Celery and CI), which can call the same logic.

Two habits make scheduled commands safe. First, make them idempotent: running twice should not duplicate work (our cleanup is idempotent because the second run finds nothing to delete). Second, make them loud on failure: a command that raises CommandError exits with a non-zero status, which schedulers and monitoring tools notice.

Where should the logic live?

For anything beyond a few lines, keep the real work in a normal function, for example in services.py, and let the command only parse arguments and print messages. The same function can then be called from a view, a task or a test. Thin commands are also easier to test: you can assert on the function's result instead of captured text. See testing Django apps for test patterns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must a custom command's module live so that manage.py can find it?

    Django scans every installed app for a management/commands package. The file name becomes the command name.
  2. 2. Which method do you override to declare command-line arguments?

    add_arguments receives an argparse parser. The parsed values arrive in handle() as the options dictionary.
  3. 3. Why write output with self.stdout.write() instead of print()?

    call_command(..., stdout=buffer) swaps in a different stream. Output sent with print() would escape that redirection.
  4. 4. What is the best way to make a command report a problem to the user and exit with failure?

    CommandError prints a clean message without a traceback and gives a non-zero exit status, which schedulers can detect.
  5. 5. How does a --dry-run option appear in the options dictionary?

    argparse converts dashes in the option name to underscores for the destination, so --dry-run becomes dry_run.

Summary

  • A management command is a Command class (subclass of BaseCommand) in <app>/management/commands/<name>.py.
  • Declare arguments in add_arguments() with argparse; read them from options in handle().
  • Print through self.stdout and self.style; fail with CommandError.
  • call_command() runs a command from Python, with command-line style or keyword arguments, and is how you test commands.
  • Give destructive commands a --dry-run, make scheduled commands idempotent, and keep real logic in plain functions.
  • Run commands on a schedule with cron, systemd timers or a task queue.

Next lesson: Caching.