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

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


当前回答

用shell_plus就简单多了

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

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

其他回答

我这样解决了这个问题。

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。

发送命令到dock -compose

几乎和上面的答案一样。

docker-compose exec service_name sh -c "
from django.contrib.auth.models import User


username = \"admin\"
email = \"admin@example.com\"
password = \"password\"
User.objects.create_superuser(username, email, password)
"

我没有提到在创建之前验证或检查用户。如果你关心这个,看看上面的答案。

我使用'./manage.py shell -c':

./manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminpass')"

它不使用额外的echo,这样做的好处是你可以将它传递给docker容器执行。不需要使用sh -c“…”,这会让你逃离地狱。

记住,首先是用户名,然后是电子邮件。

如果你有一个自定义的用户模型,你需要导入它,而不是auth.models.User

用shell_plus就简单多了

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

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

对于那些只想在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。