如何将命令行参数传递给我的Python manage.py shell脚本?

时间:2019-02-20 20:56:40

标签: django python-3.x shell authentication command-line

我有一个使用auth模块的Python 3.7 / Django项目。我想编写一个脚本来创建用户,但是我对如何做感到非常困惑。我创建了这个

from django.contrib.auth.models import User
import sys

firstarg=sys.argv[1]
secondarg=sys.argv[2]

user=User.objects.create_user(firstarg, password=secondarg)
user.is_superuser=False
user.is_staff=False
user.save()

我喜欢将用户名和密码参数传递给此脚本。我尝试了以下

localhost:dental davea$ source venv/bin/activate; python manage.py shell < create_users.py "user1" "password"
/Users/davea/Documents/workspace/dental/venv/lib/python3.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
usage: manage.py shell [-h] [--no-startup] [-i {ipython,bpython,python}]
                       [-c COMMAND] [--version] [-v {0,1,2,3}]
                       [--settings SETTINGS] [--pythonpath PYTHONPATH]
                       [--traceback] [--no-color]
manage.py shell: error: unrecognized arguments: user1 password

但是您可以看到它导致的错误。如何在创建应在其中运行的虚拟环境的同时从命令行调用脚本?

1 个答案:

答案 0 :(得分:1)

您应该通过在目录sessions中创建名为Command的类来编写custom admin command

<app>/management/commands/<your_cmd.py>

这可以让您打电话

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

class Command(BaseCommand):
    help = 'Adds a user to django'

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

    def handle(self, *args, **options):
        if User.objects.create_user(options['username'], password=options['password']):
            self.stdout.write("Successfully added user {}.".format(options['username']))

创建一个新用户。