How to make the argument of a Django management command optional?

I am trying to write a custom control command in django as shown below -

class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('delay', type=int) def handle(self, *args, **options): delay = options.get('delay', None) print delay 

Now when I run python manage.py mycommand 12 , it prints 12 on the console. What well.

Now, if I try to run python manage.py mycommand , then I want the command to print 21 on the console by default. But it gives me something like this -

 usage: manage.py mycommand [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] delay 

So, how do I make the argument to the command “not required” and accept the default value if no value is specified?

+12
source share
1 answer

One of the documentation recipes offers:

For positional arguments with nargs equal to ? or * , the default value is used if the command line argument is missing.

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

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

Using:

 $ ./manage.py mycommand 21 $ ./manage.py mycommand 4 4 
+26
source

Source: https://habr.com/ru/post/1243880/


All Articles