我想在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,这将允许您自动创建新的超级用户,但他们将无法登录,直到您为他们设置密码。
其他回答
您可以编写一个简单的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命令,它扩展了基本的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'
这样做的优点是仍然支持默认命令的使用,同时还允许使用非交互式的方式指定密码。
目前,基于Adam Charnock上述方法的解决方案已作为Python包提供。它需要三个步骤:
安装:pip Install django-createsuperuserwithpassword 激活:INSTALLED_APPS += ("django_createsuperuserwithpassword",) 应用: Python manage.py createsuperuserwithpassword \ ——用户名admin \ ——密码admin \ ——email admin@example.org \ ——保存
就是这样。
非常简单,监听post syncdb信号,从配置文件中读取超级用户凭证并应用它。
查看django-finalware和它的前身django-bootup[已弃用]
我使用'./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