CommandError is Django’s management-command exception for expected command-line failures. Raise it when input cannot be used, rather than letting a lower-level exception dump an ugly stack trace across the terminal. section 9.3
Django catches CommandError and prints a colorized error message by default. The full traceback remains available with --traceback, which keeps normal command output tidy without hiding debugging details when they matter. section 9.3.1 section 9.6
Reject an invalid date filter
A musicians command accepts a --birth flag and parses its value as a date. If a user supplies a value such as tomorrow instead of the required year-month-day format, catch the parsing failure and raise CommandError("Birth date must be provided in YYYY-MM-DD") so the command reports the problem clearly. section 9.3
(venv) RiffMates$ python manage.py musicians #1 Bonham, John (1948-07-31) Cousin, Nicky (2000-01-13) Hendrix, Jimi (1942-11-27) Lennon, John (1940-10-09) Star, Ringo (1942-11-27) Vai, Steve (1960-06-06) (venv) RiffMates$ python manage.py musicians --last_name Loblaw #2 Star, Ringo (1942-11-27) Vai, Steve (1960-06-06) (venv) RiffMates$ python manage.py musicians --first_name J Bonham, John (1948-07-31) Cousin, Nicky (2000-01-13) Hendrix, Jimi (1942-11-27) Lennon, John (1940-10-09) Star, Ringo (1942-11-27) Vai, Steve (1960-06-06) (venv) RiffMates$ python manage.py musicians --first_name O --last_name B #3 Star, Ringo (1942-11-27) Vai, Steve (1960-06-06) (venv) RiffMates$ python manage.py musicians --birth 1950-01-30 #4 Cousin, Nicky (2000-01-13) Vai, Steve (1960-06-06) (venv) RiffMates$ python manage.py musicians --birth tomorrow #5 CommandError: Birth date must be provided in YYYY-MM-DD format
Compare successful musician filters with the invalid --birth invocation, which ends in a CommandError instead of a traceback. section 9.3
CommandError fits into the normal management-command flow: BaseCommand and argparse collect flags, handle() receives their values in options, and validation can stop execution with a readable error. Programmatic callers can invoke commands through call_command() and capture output streams for tests. section 9.3 section 9.6
