我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
当前回答
目前投票最多的答案:
如果用户存在,则删除该用户,正如@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
其他回答
发送命令到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)
"
我没有提到在创建之前验证或检查用户。如果你关心这个,看看上面的答案。
非常简单,监听post syncdb信号,从配置文件中读取超级用户凭证并应用它。
查看django-finalware和它的前身django-bootup[已弃用]
目前,基于Adam Charnock上述方法的解决方案已作为Python包提供。它需要三个步骤:
安装:pip Install django-createsuperuserwithpassword 激活:INSTALLED_APPS += ("django_createsuperuserwithpassword",) 应用: Python manage.py createsuperuserwithpassword \ ——用户名admin \ ——密码admin \ ——email admin@example.org \ ——保存
就是这样。
我使用了Tk421一行,但得到了一个错误消息:1)我认为我使用的是Django(1.10)的更新版本,Manager不可用;的身份验证。用户'已被替换为'users '。User' 2) create_superuser的参数顺序错误。
所以我把它换成:
echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell
我真正满意的是,它也适用于英雄部署:
heroku run echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell
这将很好地重复工作。我在一个项目的开始使用它,所以不用担心以后可能发生的可怕的级联删除。
我已经重新访问了一些麻烦后运行这个内部local()从织物。似乎发生的事情是,管子符号意味着它是在局部而不是在heroku上得到解释。为了对它进行排序,我用引号括在命令中。然后必须在整个python命令的单引号内对python字符串使用三双引号。
heroku run "echo 'from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email="""admin@example.com""", is_superuser=True).delete(); User.objects.create_superuser("""admin""", """admin@example.com""", """nimda""")' | python manage.py shell"
您可以编写一个简单的python脚本来处理超级用户创建的自动化。User模型只是一个普通的Django模型,所以你要遵循编写独立Django脚本的正常过程。例:
import django
django.setup()
from django.contrib.auth.models import User
u = User(username='unique_fellow')
u.set_password('a_very_cryptic_password')
u.is_superuser = True
u.is_staff = True
u.save()
您还可以向createsuperuser传递一些选项,即——noinput和——username,这将允许您自动创建新的超级用户,但他们将无法登录,直到您为他们设置密码。