42đź‘Ť
In django 1.8 you should add arguments to you command:
class Command(BaseCommand):
...
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argument('password')
add_argument()
method of argparse
is documented here.
UPDATE: By default arguments are passed in the options
parameter so the handle()
method should look like this:
def handle(self, *args, **options):
username = options['username']
password = options['password']
...
And you don’t need to check the length of the args
list – it is already done by argparse
. This is the recommended method but if you want to use the args
argument then you have to use the “compatibility mode” and name the added argument as args
:
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args')
def handle(self, *args, **options):
if len(args) != 2:
...
Read the “Changed in Django 1.8” side note in the first chapter of the docs (right after the closepoll.py
example).
UPDATE2: Here is the full working example:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argument('password')
def handle(self, *args, **options):
username = options['username']
password = options['password']
return u'Username: %s Password: %s' % (username, password)
7đź‘Ť
For minimal changes just add the method add_arguments()
in Command class.
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
You can continue to use args
as before.
- [Django]-How do I create a login API using Django Rest Framework?
- [Django]-What is @csrf_exempt in Django?
- [Django]-What's the reason why Django has SmallIntegerField?