我想在django上自动运行manage.py createsuperuser,但是没有办法设置默认密码。

我怎么才能得到这个?它必须独立于django数据库。


当前回答

我喜欢使用无服务器/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.

其他回答

我使用了Tk421一行,但得到了一个错误消息:1)我认为我使用的是Django(1.10)的更新版本,Manager不可用;的身份验证。用户'已被替换为'users '。User' 2) create_superuser的参数顺序错误。

所以我把它换成:

echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell

我真正满意的是,它也适用于英雄部署:

heroku run echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email='admin@example.com', is_superuser=True).delete(); User.objects.create_superuser('admin', 'admin@example.com', 'nimda')" | python manage.py shell

这将很好地重复工作。我在一个项目的开始使用它,所以不用担心以后可能发生的可怕的级联删除。

我已经重新访问了一些麻烦后运行这个内部local()从织物。似乎发生的事情是,管子符号意味着它是在局部而不是在heroku上得到解释。为了对它进行排序,我用引号括在命令中。然后必须在整个python命令的单引号内对python字符串使用三双引号。

heroku run "echo 'from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.filter(email="""admin@example.com""", is_superuser=True).delete(); User.objects.create_superuser("""admin""", """admin@example.com""", """nimda""")' | python manage.py shell"

发送命令到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)
"

我没有提到在创建之前验证或检查用户。如果你关心这个,看看上面的答案。

非常简单,监听post syncdb信号,从配置文件中读取超级用户凭证并应用它。

查看django-finalware和它的前身django-bootup[已弃用]

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)

用shell_plus就简单多了

echo "User.objects.create_superuser('test@test.com', 'test')" | python manage.py shell_plus

正如其他人提到的,在Django 3.0中,你可以通过环境变量来传递凭证。然而,这种方法更加灵活,因为它允许您执行任何其他更复杂的任务,如删除所有测试用户等。