
Custom Django Commands
Management commands, BaseCommand, argument parsing, scheduling, cron jobs, automation
1Where should a custom Django management command file be placed to be automatically detected?
Where should a custom Django management command file be placed to be automatically detected?
回答
Custom Django management commands must be placed in the management/commands/ directory of a Django application. This directory must contain an __init__.py file in both management/ and commands/. Django automatically scans this path to discover available commands. The Python filename becomes the command name executable via manage.py.
2Which base class should be used to create a custom Django management command?
Which base class should be used to create a custom Django management command?
回答
BaseCommand is the standard base class provided by django.core.management.base for creating custom commands. It provides the necessary infrastructure: argument parsing, output color handling, error management, and integration with manage.py. The handle() method must be implemented to contain the command logic.
3How to define positional arguments in a custom Django management command?
How to define positional arguments in a custom Django management command?
回答
The add_arguments() method allows defining command arguments using the argparse parser. For positional arguments, use parser.add_argument('name') without a dash prefix. You can specify nargs for the number of expected arguments ('+' for one or more, '*' for zero or more). Arguments are then accessible via the options dictionary in handle().
Which method should be used to display a success message with appropriate colors in a Django command?
How to signal an error that stops Django command execution with a non-zero exit code?
+15 面接問題