1

I have a django command below where I can pass in a car model as an argument and it works. However, I want to add functionality to list models without needing to first pass in a model. For instance, calling python manage.py car_models --list_models would not work, as it requires something to satisfy the model arg, whereas something like python manage.py car_models Cruze --list_models would work, even though from a UX standpoint, knowing a model of car before you list it is impossible.

tl;dr, I want to have the model argument required unless the --list_models tag is in use. Anybody know a solution to this?

class Command(BaseCommand):
    help = 'Car models'

    def add_arguments(self, parser):

        parser.add_argument('model', help='model of car')

        # I want to make it so that if a user says `python manage.py car_models --list_models`, 
        # the user doesn't get yelled at for not passing in a model arg
        parser.add_argument(
            '--list_models',
            '-lm',
            dest='list_models',
            action='store_true',
            help='List available car models',
        )


    def handle(self, *args, **options):

        if options['list_models']:
            print(['Cruze', 'Tahoe', 'Impala'])
            return

        print("Your car is {}".format(options['model']))
mjkaufer
  • 4,047
  • 5
  • 27
  • 55
  • 1
    One positioinal with `nargs='?'` is accepted by a mutually exclusive group. Make that group 'required'. I may add an example later. – hpaulj Jun 28 '17 at 16:53
  • Example: https://stackoverflow.com/questions/34337653/python-argparse-mutually-exclusive-arguments-with-optional-and-positional-argu – hpaulj Jun 28 '17 at 17:26
  • @hpaulj thanks, that worked very well for me. – mjkaufer Jun 28 '17 at 18:20

0 Answers0