我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
当前回答
用shell_plus就简单多了
echo "User.objects.create_superuser('test@test.com', 'test')" | python manage.py shell_plus
正如其他人提到的,在Django 3.0中,你可以通过环境变量来传递凭证。然而,这种方法更加灵活,因为它允许您执行任何其他更复杂的任务,如删除所有测试用户等。
其他回答
在我的例子中,我们自动使用一些bash, docker, helm,我们有一些问题,转义一些逗号和引号,经过一些尝试/错误后,我们找到了最简单的方法(对我们来说最简单),这个单行命令基于之前共享的文档做到了这一点
DJANGO_SUPERUSER_PASSWORD=12345 DJANGO_SUPERUSER_USERNAME=pacho DJANGO_SUPERUSER_EMAIL=pacho@gmail.com python manage.py createsuperuser --noinput
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')"
我建议运行一个数据迁移,这样当迁移应用到项目中时,超级用户将作为迁移的一部分被创建。用户名和密码可以设置为环境变量。这在容器中运行应用程序时也很有用(以这个线程为例)。
您的数据迁移将看起来像这样:
import os
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('<your_app>', '<previous_migration>'),
] # can also be emtpy if it's your first migration
def generate_superuser(apps, schema_editor):
from django.contrib.auth.models import User
DJANGO_SU_NAME = os.environ.get('DJANGO_SU_NAME')
DJANGO_SU_EMAIL = os.environ.get('DJANGO_SU_EMAIL')
DJANGO_SU_PASSWORD = os.environ.get('DJANGO_SU_PASSWORD')
superuser = User.objects.create_superuser(
username=DJANGO_SU_NAME,
email=DJANGO_SU_EMAIL,
password=DJANGO_SU_PASSWORD)
superuser.save()
operations = [
migrations.RunPython(generate_superuser),
]
希望有帮助!
编辑: 有些人可能会提出这样的问题:如何设置这些环境变量并让Django知道它们。有很多方法,在其他SO帖子中已经回答过了,但是作为一个快速的指针,创建一个.env文件是一个好主意。然后您可以使用python-dotenv包,但是如果您已经使用pipenv设置了一个虚拟环境,它将自动在您的.env文件中设置envars。同样地,通过docker-compose运行你的应用程序可以读取你的.env文件。
目前投票最多的答案:
如果用户存在,则删除该用户,正如@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
你可以像这样在自定义命令中创建一个超级用户:
import os
from django.contrib.auth.models import User
from django.core.management import BaseCommand, call_command
from immo_project import settings
class Command(BaseCommand):
def handle(self, *args, **options):
call_command('createsuperuser', interactive=False, username='admin', email='test@example.com')
user = User.objects.get(username='admin')
user.set_password('password')
user.save()