Creating a Management Command in Django
-
Create a management and commands directory in the Django project
mkdir managementcd managementmkdir commands -
Create the empty init.py
nano __init__.py
cd commandsnano __init__.py -
Create a new command in the commands directory
nano newCommand.py -
Add the following to newCommand.py
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
args = '<command_input>'
help = 'specify help for the command'
def handle(self, *args, **options):
...
Each Python module in the commands directory will be auto-discovered and registered as a command that can be executed as an action when you run manage.py.
Each newCommand must extend Djangos BaseCommand or one of its subclasses and must reimplement the handle function (this is where the logic of the command is defined).