Django Management Command Argument

Question:

I need to pass in an integer argument to a base command in Django. For instance, if my code is:

from django.core.management import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options, number_argument):
        square = number_argument ** 2
        print(square)

I want to run:

python manage.py square_command 4

so, it will return 16.

Is there a way I can pass an argument through the terminal to the command I want to run?

Asked By: Peter Graham

||

Answers:

Yes. The mechanism for doing so is described here, but basically, you can get the argument from args[0].

Answered By: mipadi

Add this method to your Command class:

def add_arguments(self, parser):
    parser.add_argument('my_int_argument', type=int)

You can then use your option in the code, like this:

def handle(self, *args, **options):
    my_int_argument = options['my_int_argument']

The benefit of doing it this way is that the help output is automatically generated for manage.py my_command --help

Answered By: acidjunk

This is pretty simple by implementing the add_arguments method. Then, you can get the value of this argument in the handle method as follows:

class Command(BaseCommand):
    help = 'Help for command'

    def add_arguments(self, parser):
        parser.add_argument('n', type=int, help='help for n')

    def handle(self, *args, **options):
        n = options['n']
        square = n ** 2
        print(square)

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.

If you want to see the help displayed, run the following:

python manage.py square_command --help

That will produce an output similar to the following one:

usage: manage.py create_documents [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
                                  [--skip-checks]
                                  n

Help for command

positional arguments:
  n                     help for n

Answered By: lmiguelvargasf
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.