I'm trying to write a management command in django. According to the documentation default is set to False. I would assume that the default is the default value of the argument that is being passed. Make django custom management command argument "Not Required"
What's the benefit of stating that deafult=False
class Command(BaseCommand):
help = "helps in doing stuff"
def add_arguments(self, parser):
parser.add_argument(
'name', type=str, default=False,
help="The name of the folder to be created")
def handle(self, *args, **options):
pass
The first example in the docs you link to is for an optional named argument --delete
. Setting action='store_true'
means that if you include --delete
in the command, then args.delete
will be set to True
, and if --delete
is not included in the command then it will default=False
.
In this case, setting default=False
isn't actually required, because that's the behaviour of action='store_true'
. The advantage of explicitly setting default=False
is that the behaviour is clear without needing to look up the argparse
docs.
parser.add_argument(
'--delete',
action='store_true',
dest='delete',
default=False,
help='Delete poll instead of closing it',
)
Your example does not make sense, because name
is not an optional argument.
parser.add_argument(
'name', type=str, default=False,
help="The name of the folder to be created")
If you try this example then you will get an error like too few arguments
.
parser.add_argument(
'name', type=str, default=False
help="The name of the folder to be created")
You need to set nargs='?'
if you want he name
argument to be optional. In this case, your default will be used. If you didn't set it, then it will default to None
parser.add_argument(
'name', type=str, nargs='?', default=False,
help="The name of the folder to be created")
Note that if your argument is the 'name of the folder to be created', it might not make sense to set the default to False
. It seems like either the argument should be required (in which case no default is needed) or the default should be a string e.g. /path/to/folder/
.