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

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


当前回答

对于那些只想在AWS Elastic Beanstalk上托管django网站的人(即使没有docker),并且被超级用户部分卡住了,在.platform > hooks > postdeploy中创建一个名为01_migration .sh的文件,并输入以下内容:

#!/bin/bash

source /var/app/venv/*/bin/activate && { python migrate.py createsuperuser --noinput; }

然后,您可以将DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL添加到应用程序环境的配置部分。

然后将以下文件添加到.ebextentions > django.config文件夹中

container_commands:
    01_chmod1:
         command: "chmod +x .platform/hooks/postdeploy/01_migrate.sh"

这将以一种安全的方式创建超级用户,使用相同的逻辑,您还可以通过添加到01_migration .sh文件来运行迁移和collectstatic。

其他回答

我喜欢使用无服务器/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.

目前投票最多的答案:

如果用户存在,则删除该用户,正如@Groady在评论中指出的那样,您可能会无意中通过级联删除删除任何相关记录。 通过邮件检查超级用户是否存在,如果两个超级用户有相同的邮件,天知道它会删除哪一个。 更新脚本参数:用户名、密码和邮件非常麻烦。 不记录它所做的事情。

改进后的版本如下:

USER="admin"
PASS="super_password"
MAIL="admin@mail.com"
script="
from django.contrib.auth.models import User;

username = '$USER';
password = '$PASS';
email = '$MAIL';

if User.objects.filter(username=username).count()==0:
    User.objects.create_superuser(username, email, password);
    print('Superuser created.');
else:
    print('Superuser creation skipped.');
"
printf "$script" | python manage.py shell

如果您直接引用User,您的代码将无法在AUTH_USER_MODEL设置已更改为不同用户模型的项目中工作。创建用户的一种更通用的方法是:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'password')" | python manage.py shell

原来的答案

这里有一个简单的脚本版本来创建一个超级用户:

echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" | python manage.py shell

对于那些只想在AWS Elastic Beanstalk上托管django网站的人(即使没有docker),并且被超级用户部分卡住了,在.platform > hooks > postdeploy中创建一个名为01_migration .sh的文件,并输入以下内容:

#!/bin/bash

source /var/app/venv/*/bin/activate && { python migrate.py createsuperuser --noinput; }

然后,您可以将DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL添加到应用程序环境的配置部分。

然后将以下文件添加到.ebextentions > django.config文件夹中

container_commands:
    01_chmod1:
         command: "chmod +x .platform/hooks/postdeploy/01_migrate.sh"

这将以一种安全的方式创建超级用户,使用相同的逻辑,您还可以通过添加到01_migration .sh文件来运行迁移和collectstatic。

我这样解决了这个问题。

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。