Reputation: 65510
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?
Upvotes: 4
Views: 3083
Reputation: 8601
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.
Upvotes: 6
Reputation: 51
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.
Upvotes: 5