I need to pass in an integer argument to a base command in Django. For instance, if my code is:
JavaScript
x
7
1
from django.core.management import BaseCommand
2
3
class Command(BaseCommand):
4
def handle(self, *args, **options, number_argument):
5
square = number_argument ** 2
6
print(square)
7
I want to run:
JavaScript
1
2
1
python manage.py square_command 4
2
so, it will return 16.
Is there a way I can pass an argument through the terminal to the command I want to run?
Advertisement
Answer
Add this method to your Command class:
JavaScript
1
3
1
def add_arguments(self, parser):
2
parser.add_argument('my_int_argument', type=int)
3
You can then use your option in the code, like this:
JavaScript
1
3
1
def handle(self, *args, **options):
2
my_int_argument = options['my_int_argument']
3
The benefit of doing it this way is that the help
output is automatically generated for manage.py my_command --help