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?
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With