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?
Advertisement
Answer
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