Django自定义命令错误:无法识别的参数

时间:2022-06-11 02:49:26

I'm trying to create a command similar to createsuperuser which will take two arguments (username and password)

我正在尝试创建一个类似于createsuperuser的命令,它将采用两个参数(用户名和密码)

Its working fine in django 1.7 but not in 1.8. (I'm also using python3.4)

它在django 1.7中运行良好,但在1.8中没有。 (我也使用python3.4)

this is the code I wrote

这是我写的代码

myapp/management/commands/createmysuperuser.py

MyApp的/管理/命令/ createmysuperuser.py

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User


class Command(BaseCommand):
    help = 'Create a super user'

    def handle(self, *args, **options):

        if len(args) != 2:
            raise CommandError('need exactly two arguments for username and password')
        username, password = args

        u, created = User.objects.get_or_create(username=username)
        if created:
            u.is_superuser = True
            u.is_staff = True
            u.set_password(password)
            u.save()
        else:
            raise CommandError("user '%s' already exist" % username)

        return "Password changed successfully for user '%s'" % u.username

and when I try to run this command

当我尝试运行此命令时

$ python manage.py createmysuperuser myuser mypassword

$ python manage.py createmysuperuser myuser mypassword

I get this error

我收到这个错误

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

but when I dont pass any arguments it raises CommandError which is expected.

但是当我没有传递任何参数时,它会引发预期的CommandError。

CommandError: need exactly two arguments for username and password

CommandError:需要两个用户名和密码参数

1 个解决方案

#1


30  

In django 1.8 you should add arguments to you command:

在django 1.8中,你应该为你的命令添加参数:

class Command(BaseCommand):
    ...
    def add_arguments(self, parser):
        parser.add_argument('username')
        parser.add_argument('password')

add_argument() method of argparse is documented here.

这里记录了argparse的add_argument()方法。

UPDATE: By default arguments are passed in the options parameter so the handle() method should look like this:

更新:默认情况下,参数在options参数中传递,因此handle()方法应如下所示:

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:

而且你不需要检查args列表的长度 - 它已经由argparse完成了。这是推荐的方法,但是如果要使用args参数,则必须使用“兼容模式”并将添加的参数命名为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).

阅读文档第一章中的“更改Django 1.8”旁注(紧跟在closepoll.py示例之后)。

UPDATE2: Here is the full working example:

UPDATE2:这是完整的工作示例:

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)

#1


30  

In django 1.8 you should add arguments to you command:

在django 1.8中,你应该为你的命令添加参数:

class Command(BaseCommand):
    ...
    def add_arguments(self, parser):
        parser.add_argument('username')
        parser.add_argument('password')

add_argument() method of argparse is documented here.

这里记录了argparse的add_argument()方法。

UPDATE: By default arguments are passed in the options parameter so the handle() method should look like this:

更新:默认情况下,参数在options参数中传递,因此handle()方法应如下所示:

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:

而且你不需要检查args列表的长度 - 它已经由argparse完成了。这是推荐的方法,但是如果要使用args参数,则必须使用“兼容模式”并将添加的参数命名为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).

阅读文档第一章中的“更改Django 1.8”旁注(紧跟在closepoll.py示例之后)。

UPDATE2: Here is the full working example:

UPDATE2:这是完整的工作示例:

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)