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

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


当前回答

我使用'./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

其他回答

我使用'./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

目前投票最多的答案:

如果用户存在,则删除该用户,正如@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
DJANGO_SUPERUSER_USERNAME=testuser \
DJANGO_SUPERUSER_PASSWORD=testpass \
DJANGO_SUPERUSER_EMAIL="admin@admin.com" \
python manage.py createsuperuser --noinput

createuser命令的文档

python manage.py shell -c "from django.contrib.auth.models import User; \
                           User.objects.filter(username='admin1').exists() or \
                           User.objects.create_superuser('admin1',
                           'admin1@example.com', 'admin1')"

在我的例子中,我们自动使用一些bash, docker, helm,我们有一些问题,转义一些逗号和引号,经过一些尝试/错误后,我们找到了最简单的方法(对我们来说最简单),这个单行命令基于之前共享的文档做到了这一点

DJANGO_SUPERUSER_PASSWORD=12345 DJANGO_SUPERUSER_USERNAME=pacho DJANGO_SUPERUSER_EMAIL=pacho@gmail.com python manage.py createsuperuser --noinput