Photo by Emile Perron on Unsplash

Create custom management commands in Django framework

custom_app/
__init__.py
models.py
management/
commands/
_private.py
show_date.py
tests.py
views.py

Basic Example

python manage.py show_date
from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = 'Displays current time'
def handle(self, *args, **kwargs):
time = timezone.now().strftime('%X')
self.stdout.write("It's now %s" % time)

Positional Arguments

from django.core.management.base import BaseCommand
from django.utils import timezone
class 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

from django.core.management.base import BaseCommand
from django.utils import timezone
class 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)
python manage.py show_date test_me --delete=True

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store