I'm trying to create a Django management command with argparse, however whenever I run it, it always returns no such option which is valid, as this message comes from the manage.py:
class Command(BaseCommand):
def handle(self, *args, **options):
parser = argparse.ArgumentParser('Parsing arguments')
parser.add_argument('--max', type=float, store)
args = parser.parse_args(sys.argv[2:])
What would be the right way to use some argument parser with management commands?
Python version 2.x .
-
2It's worth noting that Django now uses argparse instead of optparse as of Django 1.8 docs.djangoproject.com/en/1.8/howto/custom-management-commandsmrpopo– mrpopo2015年09月14日 15:15:21 +00:00Commented Sep 14, 2015 at 15:15
3 Answers 3
In Django options are parsed with rules given in add_arguments method of BaseCommand. You should add your options to parser.add_argument, which use argparse lib like this:
class Command(BaseCommand):
help = 'My cool command'
def add_arguments(self, parser):
# Named (optional) arguments
parser.add_argument(
'--max',
action='store',
dest='max',
type='float',
default=0.0,
help='Max value'
)
def handle(self, *args, **options):
print options['max']
1 Comment
Instead, just modify the option_list, as suggested in docs:
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--max',
action='store',
type='float',
dest='max'),
)
def handle(self, *args, **options):
print options['max']
1 Comment
According to the docs, custom options can be added in the add_arguments() method.
class Command(BaseCommand):
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('poll_id', nargs='+', type=int)
# Named (optional) arguments
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
help='Delete poll instead of closing it',
)
def handle(self, *args, **options):
# ...
if options['delete']:
poll.delete()
# ...