5

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 Answer 1

7

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.