Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Management Command Argument

Tags:

python

django

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?

like image 981
Peter Graham Avatar asked Dec 22 '14 22:12

Peter Graham


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 Django management command?

Django management commands are included as part of Django apps and are designed to fulfill repetitive or complex tasks through a one keyword command line instruction. Every Django management command is backed by a script that contains the step-by-step Python logic to fulfill its duties.


1 Answers

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

like image 152
acidjunk Avatar answered Sep 18 '22 13:09

acidjunk