Create custom management commands in Django framework
Django comes with a variety of command line utilities that can be invoked using manage.py
script. In addition to all existing commands (like this command to create a new app:python manage.py startapp custom
) you can also add your own commands. These custom management commands can be very useful when you need to interact with your application via command line using a terminal and it can also serve as an interface to execute recurring jobs.
Each application in django can have their own commands. you can add new commands by creating a management/commands directory inside an app directory. Django will register a manage.py
command for each Python module in that directory whose name doesn’t begin with an underscore:
custom_app/
__init__.py
models.py
management/
commands/
_private.py
show_date.py
tests.py
views.py
Basic Example
In this example _private.py won’t be registered in django manage.py
commands but show_date.py command will be registered and you can run it using:
python manage.py show_date
Now let’s demonstrate a basic example of what the our custom command should look like:
management/commands/show_date.py
from django.core.management.base import BaseCommand
from django.utils import timezoneclass Command(BaseCommand):
help = 'Displays current time' def handle(self, *args, **kwargs):
time = timezone.now().strftime('%X')
self.stdout.write("It's now %s" % time)
A Django management command is a child of BaseCommand
composed by a class named Command
. The command code should be defined inside the handle()
method.
Positional Arguments
You can add optional arguments to the custom command using add_arguments()
from django.core.management.base import BaseCommand
from django.utils import timezoneclass Command(BaseCommand):
help = 'Displays current time' def add_arguments(self, parser):
# Positional arguments
parser.add_argument('test', nargs='+', type=int) def handle(self, *args, **kwargs):
for arg in kwargs['test']:
print(arg) time = timezone.now().strftime('%X')
self.stdout.write("It's now %s" % time)
Optional Arguments
To add custom options to command you can add named argument to the command
from django.core.management.base import BaseCommand
from django.utils import timezoneclass Command(BaseCommand):
help = 'Displays current time' def add_arguments(self, parser):
# Positional arguments
parser.add_argument('test', nargs='+', type=int) # Named (optional) arguments
parser.add_argument(
'--delete',
action='store_true',
help='Delete something',
) def handle(self, *args, **kwargs):
for arg in kwargs['test']:
print(arg) time = timezone.now().strftime('%X')
self.stdout.write("It's now %s" % time)
You can run show_date custom command with arguments like this:
python manage.py show_date test_me --delete=True
Source: