Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I am trying to write a custom management command in django like 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 am running python manage.py mycommand 12 it is printing 12 on console. Which is fine.

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

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

So now, how should I make the command argument "not required" and take a default value if value is not given?

like image 608
Tanvir Hossain Bhuiyan Avatar asked Feb 25 '16 18:02

Tanvir Hossain Bhuiyan


People also ask

How do you pass arguments in Django management command?

The parameter parser is an instance of argparse. ArgumentParser (see the docs). Now you can add as many arguments as you want by calling parser 's add_argument method. In the code above, you are expecting a parameter n of type int which is gotten in the handle method from options .

What is BaseCommand Django?

BaseCommand is a Django object for creating new Django admin commands that can be invoked with the manage.py script. The Django project team as usual provides fantastic documentation for creating your own commands.


1 Answers

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 mycommand 21 $ ./manage.py mycommand 4 4 
like image 70
Yaroslav Admin Avatar answered Sep 18 '22 05:09

Yaroslav Admin