Django custom management command - adding default values for arguments

Viewed 1283

I am using Django 2.2 and I want to write to add a custom task (for an app) that loads fixtures into database tables.

This is what I have so far:

from django.core.management.base import BaseCommand
from django.core import management


class Command(BaseCommand):
    help = 'Generate Capture Data from loaded fixtures'

    def add_arguments(self, parser):
        parser.add_argument('definitions', type=str, help='Name of the definitions fixtures file', default='definitions.json')
        parser.add_argument('sections', type=str, help='Name of the sections fixtures file', default='sections.json')
        parser.add_argument('questions', type=str, help='Name of the questions fixtures file', default='questions.json')


    def handle(self, *args, **kwargs):
        print(kwargs)

However, when I run python manage.py generate_data, I get the following exception thrown:

usage: manage.py generate_data [-h] [--version] [-v {0,1,2,3}]
                                    [--settings SETTINGS]
                                    [--pythonpath PYTHONPATH] [--traceback]
                                    [--no-color] [--force-color]
                                    definitions sections questions
manage.py generate_data: error: the following arguments are required: definitions, sections, questions

Why are the defaults I provide to add_arguments() being ignored?

1 Answers

You probably need to use nargs. One of the cases, according to docs:

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

So, the code will be:

    parser.add_argument('definitions',  nargs='?', type=str, help='Name of the definitions fixtures file', default='definitions.json')
    parser.add_argument('sections',  nargs='?', type=str, help='Name of the sections fixtures file', default='sections.json')
    parser.add_argument('questions',  nargs='?', type=str, help='Name of the questions fixtures file', default='questions.json')
Related