我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。
我怎么才能得到这个?它必须独立于django数据库。
当前回答
非常简单,监听post syncdb信号,从配置文件中读取超级用户凭证并应用它。
查看django-finalware和它的前身django-bootup[已弃用]
其他回答
我喜欢使用无服务器/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.
在我的例子中,我们自动使用一些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')"
发送命令到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)
"
我没有提到在创建之前验证或检查用户。如果你关心这个,看看上面的答案。
Python manage.py shell < mysite/create_superuser.py
我的网站/create_superuser.py
from decouple import config
from django.db import IntegrityError
# getting name,email & password from env variables
DJANGO_SU_NAME = config('DJANGO_SU_NAME')
DJANGO_SU_EMAIL = config('DJANGO_SU_EMAIL')
DJANGO_SU_PASSWORD = config('DJANGO_SU_PASSWORD')
try:
superuser = User.objects.create_superuser(
username=DJANGO_SU_NAME,
email=DJANGO_SU_EMAIL,
password=DJANGO_SU_PASSWORD)
superuser.save()
except IntegrityError:
print(f"Super User with username {DJANGO_SU_NAME} is already present")
except Exception as e:
print(e)