42

I want to implement import feature with required and optional parameters, to run this in this way:

python manage.py import --mode archive

where --mode is required and archive also.

I'm using argparse library.

class Command(BaseCommand):
    help = 'Import'

    def add_arguments(self, parser):
        parser.add_argument('--mode',
            required=True,
        )
        parser.add_argument('archive',
            required=True,
            default=False,
            help='Make import archive events'
        )

But I recived error:

TypeError: 'required' is an invalid argument for positionals
Kai
  • 553
  • 3
  • 7
  • 15

2 Answers2

68

You created a positional argument (no -- option in front of the name). Positional arguments are always required. You can't use required=True for such options, just drop the required. Drop the default too; a required argument can't have a default value (it would never be used anyway):

parser.add_argument('archive',
    help='Make import archive events'
)

If you meant for archive to be a command-line switch, use --archive instead.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 4
    Note that although they're always required, one can define them to be empty with `nargs`. See https://stackoverflow.com/q/4480075/333599 . – Calimo Mar 18 '21 at 09:48
  • @Calimo: that would only work for the last positional argument, however. And in this case, the OP wanted the positional argument to be mandatory, not optional. – Martijn Pieters Mar 21 '21 at 13:15
2

I think that --mode archive is supposed to mean "mode is archive", in other words archive is the value of the --mode argument, not a separate argument. If it were, it would have to be --archive which is not what you want.

Just leave out the definition of archive.

BoarGules
  • 16,440
  • 2
  • 27
  • 44