pythondjangodjango-commands

Modifying Django Command argument


Lets say i have a command like:

class Command(object):
    help = 'roll over and die'

    def add_arguments(self, parser):
        parser.add_argument(
            '--foo',
            help='see command help',
            choices=['die','die_painfully'],
            required=True
        )
        parser.add_agument( ... )          x 9001

and now i want to have an almost identical class but i dont want the argument '--foo' to required anymore. Can u modify that parser somehow if i super the hole add_arguments in the inhering method or something?


Solution

  • You could use a class attribute:

    class Command(object):
        help = 'roll over and die'
        foo_required = True
    
        def add_arguments(self, parser):
            parser.add_argument(
                '--foo',
                # ...
                required=self.foo_required
            )
    

    and then in inheriting Command:

    class Command(foo.bar.Command):
        foo_required = False
    

    and you wouldn't have to override add_arguments.