我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。

我怎么才能得到这个?它必须独立于django数据库。


当前回答

进入命令提示符并输入:

C:\WINDOWS\system32>pip install django-createsuperuser
Collecting django-createsuperuser
  Downloading https://files.pythonhosted.org/packages/93/8c/344c6367afa62b709adebee039d09229675f1ee34d424180fcee9ed857a5/django-createsuperuser-2019.4.13.tar.gz
Requirement already satisfied: Django>1.0 in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (2.2.1)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (41.0.1)
Requirement already satisfied: sqlparse in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (0.3.0)
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (2018.7)
Building wheels for collected packages: django-createsuperuser
  Running setup.py bdist_wheel for django-createsuperuser ... done
  Stored in directory: C:\Users\Arif Khan\AppData\Local\pip\Cache\wheels\0c\96\2a\e73e95bd420e844d3da1c9d3e496c92642a4f2181535440db2
Successfully built django-createsuperuser
Installing collected packages: django-createsuperuser

如果没有执行迁移,那么转到django应用程序文件夹并执行以下命令

Python manage.py迁移 Python manage.py创建超级用户

宾果。

其他回答

目前,基于Adam Charnock上述方法的解决方案已作为Python包提供。它需要三个步骤:

安装:pip Install django-createsuperuserwithpassword 激活:INSTALLED_APPS += ("django_createsuperuserwithpassword",) 应用: Python manage.py createsuperuserwithpassword \ ——用户名admin \ ——密码admin \ ——email admin@example.org \ ——保存

就是这样。

我这样解决了这个问题。

Wsgi.py文件总是在django项目启动时运行。如果它不存在,我运行create super user命令。

import os

from django.contrib.auth.models import User
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', {settings_file})

application = get_wsgi_application()

users = User.objects.all()
if not users:
    User.objects.create_superuser(username="username", email="user@example.com", password="password", is_active=True, is_staff=True)

这里可以添加一个函数。例如;如果这个user1不存在,添加user1。

我自己也在寻找答案。我决定创建一个Django命令,它扩展了基本的createsuperuser命令(GitHub):

from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError


class Command(createsuperuser.Command):
    help = 'Crate a superuser, and allow password to be provided'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--password', dest='password', default=None,
            help='Specifies the password for the superuser.',
        )

    def handle(self, *args, **options):
        password = options.get('password')
        username = options.get('username')
        database = options.get('database')

        if password and not username:
            raise CommandError("--username is required if specifying --password")

        super(Command, self).handle(*args, **options)

        if password:
            user = self.UserModel._default_manager.db_manager(database).get(username=username)
            user.set_password(password)
            user.save()

使用示例:

./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email 'blank@email.com'

这样做的优点是仍然支持默认命令的使用,同时还允许使用非交互式的方式指定密码。

用shell_plus就简单多了

echo "User.objects.create_superuser('test@test.com', 'test')" | python manage.py shell_plus

正如其他人提到的,在Django 3.0中,你可以通过环境变量来传递凭证。然而,这种方法更加灵活,因为它允许您执行任何其他更复杂的任务,如删除所有测试用户等。

我喜欢使用无服务器/docker构建AppConfig。Ready方法/事件来执行这种操作,这里有一个例子:

import logging

from django.apps import AppConfig
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as gettext


class Config(AppConfig):
    name: str = "apps.policy"
    label: str = "policy"
    verbose_name: str = gettext("Policies")

    @classmethod
    def ready(cls):
        user_model = get_user_model()
        log = logging.getLogger(cls.label)

        try:
            if not user_model.objects.filter(username="admin").first():
                log.info("Creating default superuser with user and password: admin")
                user_model.objects.create_superuser('admin', 'admin@admin.admin', 'admin')
        except Exception:
            log.warn(
                "Found an error trying to create the superuser, if you aren't"
                "run the user model migration yet, ignore this message"
            )

当我第一次在数据库中启动我的项目时,我看到:

2021-06-22 06:19:02 policy/info  Creating default superuser with user and password: admin
Performing system checks...

System check identified no issues (1 silenced).
June 22, 2021 - 06:19:02
Django version 3.1.12, using settings 'settings.env.default'
Starting development server at http://0.0.0.0:8027/
Quit the server with CONTROL-C.