How to make a Django custom management command argument not required? How to make a Django custom management command argument not required? python python

How to make a Django custom management command argument not required?


One of the recipes from the documentation suggests:

For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present.

So following should do the trick (it will return value if provided or default value otherwise):

parser.add_argument('delay', type=int, nargs='?', default=21)

Usage:

$ ./manage.py mycommand21$ ./manage.py mycommand 44


You can use the dash syntax for optional keyword arguments:

class Command(BaseCommand):    def add_arguments(self, parser):        parser.add_argument("-d", "--delay", type=int)    def handle(self, *args, **options):        delay = options["delay"] if options["delay"] else 21        print(delay)

Use:

$ python manage.py mycommand -d 44$ python manage.py mycommand --delay 44$ python manage.py mycommand21

Docs:

https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/#s-accepting-optional-arguments

Simple explanation:

https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html#handling-arguments