我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
当前回答
进入命令提示符并输入:
C:\WINDOWS\system32>pip install django-createsuperuser
Collecting django-createsuperuser
Downloading https://files.pythonhosted.org/packages/93/8c/344c6367afa62b709adebee039d09229675f1ee34d424180fcee9ed857a5/django-createsuperuser-2019.4.13.tar.gz
Requirement already satisfied: Django>1.0 in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (2.2.1)
Requirement already satisfied: setuptools in c:\programdata\anaconda3\lib\site-packages (from django-createsuperuser) (41.0.1)
Requirement already satisfied: sqlparse in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (0.3.0)
Requirement already satisfied: pytz in c:\programdata\anaconda3\lib\site-packages (from Django>1.0->django-createsuperuser) (2018.7)
Building wheels for collected packages: django-createsuperuser
Running setup.py bdist_wheel for django-createsuperuser ... done
Stored in directory: C:\Users\Arif Khan\AppData\Local\pip\Cache\wheels\0c\96\2a\e73e95bd420e844d3da1c9d3e496c92642a4f2181535440db2
Successfully built django-createsuperuser
Installing collected packages: django-createsuperuser
如果没有执行迁移,那么转到django应用程序文件夹并执行以下命令
Python manage.py迁移 Python manage.py创建超级用户
宾果。
其他回答
我喜欢使用无服务器/docker构建AppConfig。Ready方法/事件来执行这种操作,这里有一个例子:
import logging
from django.apps import AppConfig
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as gettext
class Config(AppConfig):
name: str = "apps.policy"
label: str = "policy"
verbose_name: str = gettext("Policies")
@classmethod
def ready(cls):
user_model = get_user_model()
log = logging.getLogger(cls.label)
try:
if not user_model.objects.filter(username="admin").first():
log.info("Creating default superuser with user and password: admin")
user_model.objects.create_superuser('admin', 'admin@admin.admin', 'admin')
except Exception:
log.warn(
"Found an error trying to create the superuser, if you aren't"
"run the user model migration yet, ignore this message"
)
当我第一次在数据库中启动我的项目时,我看到:
2021-06-22 06:19:02 policy/info Creating default superuser with user and password: admin
Performing system checks...
System check identified no issues (1 silenced).
June 22, 2021 - 06:19:02
Django version 3.1.12, using settings 'settings.env.default'
Starting development server at http://0.0.0.0:8027/
Quit the server with CONTROL-C.
我自己也在寻找答案。我决定创建一个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'
这样做的优点是仍然支持默认命令的使用,同时还允许使用非交互式的方式指定密码。
这是我为Heroku post_deploy和一个预定义的app.json变量拼凑起来的:
if [[ -n "$CREATE_SUPER_USER" ]]; then
echo "==> Creating super user"
cd /app/example_project/src
printf "from django.contrib.auth.models import User\nif not User.objects.exists(): User.objects.create_superuser(*'$CREATE_SUPER_USER'.split(':'))" | python /app/example_project/manage.py shell
fi
这样你可以有一个单独的env变量:
CREATE_SUPER_USER=admin:admin@example.com:password
我喜欢shell——command选项,但不确定如何在命令脚本中获得换行符。如果没有换行符,if表达式会导致语法错误。
发送命令到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)
"
我没有提到在创建之前验证或检查用户。如果你关心这个,看看上面的答案。
如果您直接引用User,您的代码将无法在AUTH_USER_MODEL设置已更改为不同用户模型的项目中工作。创建用户的一种更通用的方法是:
echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@myproject.com', 'password')" | python manage.py shell
原来的答案
这里有一个简单的脚本版本来创建一个超级用户:
echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" | python manage.py shell