我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
当前回答
您可以编写一个简单的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,这将允许您自动创建新的超级用户,但他们将无法登录,直到您为他们设置密码。
其他回答
DJANGO_SUPERUSER_USERNAME=testuser \
DJANGO_SUPERUSER_PASSWORD=testpass \
DJANGO_SUPERUSER_EMAIL="admin@admin.com" \
python manage.py createsuperuser --noinput
createuser命令的文档
目前投票最多的答案:
如果用户存在,则删除该用户,正如@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
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
# The magic line
User.objects.create_user(username= 'rmx',
email='superuser@super.com',
password='rmx55',
is_staff=True,
is_active=True,
is_superuser=True
)
用shell_plus就简单多了
echo "User.objects.create_superuser('test@test.com', 'test')" | python manage.py shell_plus
正如其他人提到的,在Django 3.0中,你可以通过环境变量来传递凭证。然而,这种方法更加灵活,因为它允许您执行任何其他更复杂的任务,如删除所有测试用户等。
我自己也在寻找答案。我决定创建一个Django命令,它扩展了基本的createsuperuser命令(GitHub):
from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError
class Command(createsuperuser.Command):
help = 'Crate a superuser, and allow password to be provided'
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
'--password', dest='password', default=None,
help='Specifies the password for the superuser.',
)
def handle(self, *args, **options):
password = options.get('password')
username = options.get('username')
database = options.get('database')
if password and not username:
raise CommandError("--username is required if specifying --password")
super(Command, self).handle(*args, **options)
if password:
user = self.UserModel._default_manager.db_manager(database).get(username=username)
user.set_password(password)
user.save()
使用示例:
./manage.py createsuperuser2 --username test1 --password 123321 --noinput --email 'blank@email.com'
这样做的优点是仍然支持默认命令的使用,同时还允许使用非交互式的方式指定密码。