Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django management command cannot see arguments?

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?

like image 402
Richard Avatar asked Oct 26 '25 06:10

Richard


2 Answers

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.

like image 142
Vlad Schnakovszki Avatar answered Oct 28 '25 22:10

Vlad Schnakovszki


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.

like image 34
CodeMagnet Avatar answered Oct 28 '25 20:10

CodeMagnet