4

Since upgrading to Django 1.8, there's a strange bug in my Django management command.

I run it as follows:

python manage.py my_command $DB_NAME $DB_USER $DB_PASS

And then I collect the arguments as follows:

class Command(BaseCommand):

def handle(self, *args, **options):
    print args
    db_name = args[0]
    db_user = args[1]
    db_pass = args[2]
    self.conn = psycopg2.connect(database=db_name, user=db_user,
                                 password=db_pass)

Previously this worked fine, but now I see this error:

usage: manage.py my_command [-h] [--version] [-v {0,1,2,3}]
                                             [--settings SETTINGS]
                                             [--pythonpath PYTHONPATH]
                                             [--traceback] [--no-color]
manage.py my_command: error: unrecognized arguments: test test test

It's not even getting as far as the print args statement.

If I run it without any arguments, then it errors on the args[0] line, unsurprisingly.

Am I using args wrong here? Or is something else going on?

1
  • 1
    Is this a real case scenario? There is already dbshell in Django. You're reinventing the wheel. You can call the DB command line with python manage.py dbshell. Commented Jan 18, 2018 at 9:28

2 Answers 2

6

It is a change in Django 1.8. As detailed here:

Management commands that only accept positional arguments

If you have written a custom management command that only accepts positional arguments and you didn’t specify the args command variable, you might get an error like Error: unrecognized arguments: ..., as variable parsing is now based on argparse which doesn’t implicitly accept positional arguments. You can make your command backwards compatible by simply setting the args class variable. However, if you don’t have to keep compatibility with older Django versions, it’s better to implement the new add_arguments() method as described in Writing custom django-admin commands.

Sign up to request clarification or add additional context in comments.

Comments

5
def add_arguments(self, parser):
    parser.add_argument('args', nargs='*')

Add the above for compatibility, breaking it was a really unwise decision from the folks updating the django.

1 Comment

This is the right way to specify the arguments. However I don't agree that it was really unwise. Sometimes you have to break with the past and move forward.

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.