Django control command can't see arguments?

Since upgrading to Django 1.8, a strange error appears in my Django management team.

I run it like this:

python manage.py my_command $DB_NAME $DB_USER $DB_PASS

      

And then I collect the arguments like this:

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)

      

This used to work 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 doesn't even reach the operator print args

.

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

, no wonder.

Am I using args

it wrong here? Or is something else going on?

+3


source to share


2 answers


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



Control commands that only accept positional arguments¶

If you wrote a custom control command that only takes positional arguments, and you didn’t specify the command variable args, you might get an error such as Error: unrecognized arguments: ..., since the parsing of variables is now based on argparse, which doesn’t implicitly take positional arguments. You can make your command backward compatible by simply setting the args class variable. However, if you don’t need to maintain compatibility with older versions of Django, it’s better to implement the new add_arguments () method, as described in Writing Custom django-admin Commands.

+5


source


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

      



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

+3


source







All Articles