Full answer
Management commands are scripts that run with the project's settings, models and apps loaded. Built-in ones include migrate, createsuperuser and shell. Custom commands suit jobs such as sending fee reminders, importing a CSV of new admissions or cleaning old sessions.
File layout: attendance/management/commands/mark_absent.py (both management/ and commands/ need __init__.py). The file name becomes the command name.
class Command(BaseCommand):
help = "Mark students absent who did not check in"
def add_arguments(self, parser):
parser.add_argument("date")
parser.add_argument("--dry-run", action="store_true")
def handle(self, *args, **options):
...Good practices:
- Use
self.stdout.write()andself.stderr.write()instead ofprint, so tests andcall_commandcan capture output.self.style.SUCCESS(...)andself.style.ERROR(...)add colour in terminals. - Raise
CommandError("message")for expected failures; it prints the message and exits with a non-zero code, which cron and CI notice. - Add
--dry-runfor anything that changes or deletes data. - Process large data sets in batches with
iterator()and wrap each batch intransaction.atomic(). - Make the command safe to run twice (idempotent), because schedulers retry.
- Respect
--verbosity(options["verbosity"]). - Test with
call_command("mark_absent", "2026-12-04", dry_run=True, stdout=StringIO()).
Scheduling is outside Django: cron, Kubernetes CronJobs, systemd timers or a task queue scheduler such as Celery beat run the command.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from io import StringIO
from django.core.management.base import BaseCommand, CommandError
from django.db import models, connection
class Attendance(models.Model):
roll_no = models.IntegerField()
date = models.DateField()
status = models.CharField(max_length=10, default="unknown")
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Attendance)
for r in (1, 2, 3):
Attendance.objects.create(roll_no=r, date="2026-12-04", status="present" if r == 2 else "unknown")
class Command(BaseCommand):
help = "Mark students absent who have no check-in for the given date"
def add_arguments(self, parser):
parser.add_argument("date")
parser.add_argument("--dry-run", action="store_true")
def handle(self, *args, **options):
qs = Attendance.objects.filter(date=options["date"], status="unknown")
if not Attendance.objects.filter(date=options["date"]).exists():
raise CommandError(f"No attendance sheet for {options['date']}")
if options["dry_run"]:
self.stdout.write(f"Would mark {qs.count()} students absent")
return
changed = qs.update(status="absent")
self.stdout.write(self.style.SUCCESS(f"Marked {changed} students absent"))
def run(*argv):
out = StringIO()
cmd = Command(stdout=out)
parser = cmd.create_parser("manage.py", "mark_absent")
options = vars(parser.parse_args(argv))
cmd.execute(**options)
return out.getvalue().strip()
print(run("2026-12-04", "--dry-run"))
print(run("2026-12-04", "--no-color"))
print(run("2026-12-04", "--no-color")) # safe to run again
try:
run("2026-12-05")
except CommandError as e:
print("CommandError:", e)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. In a project the class lives in attendance/management/commands/mark_absent.py and you call it with call_command or manage.py; here it is parsed and executed directly. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Would mark 2 students absent Marked 2 students absent Marked 0 students absent CommandError: No attendance sheet for 2026-12-05
Key points
- Path: app/management/commands/<name>.py with class Command(BaseCommand)
- add_arguments() for options, handle() for the work
- self.stdout and CommandError instead of print and sys.exit
- --dry-run and idempotency for data-changing jobs
- Test with call_command()
Common mistakes
- Using print() so output cannot be captured in tests
- Calling sys.exit() instead of raising CommandError
- Loading millions of rows into memory at once
- Writing commands that double-apply changes when re-run
Follow-ups
- How would you schedule this command in production?
- How do you test a command that reads a CSV file?
- When would a task queue be better than a management command?
Tips
- Show the file path, it is a common gotcha
- Mention dry-run and idempotency
- Talk about how the command is scheduled and monitored