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

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


当前回答

在我的例子中,我们自动使用一些bash, docker, helm,我们有一些问题,转义一些逗号和引号,经过一些尝试/错误后,我们找到了最简单的方法(对我们来说最简单),这个单行命令基于之前共享的文档做到了这一点

DJANGO_SUPERUSER_PASSWORD=12345 DJANGO_SUPERUSER_USERNAME=pacho DJANGO_SUPERUSER_EMAIL=pacho@gmail.com python manage.py createsuperuser --noinput

其他回答

DJANGO_SUPERUSER_USERNAME=testuser \
DJANGO_SUPERUSER_PASSWORD=testpass \
DJANGO_SUPERUSER_EMAIL="admin@admin.com" \
python manage.py createsuperuser --noinput

createuser命令的文档

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
        )

我这样解决了这个问题。

Wsgi.py文件总是在django项目启动时运行。如果它不存在,我运行create super user命令。

import os

from django.contrib.auth.models import User
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', {settings_file})

application = get_wsgi_application()

users = User.objects.all()
if not users:
    User.objects.create_superuser(username="username", email="user@example.com", password="password", is_active=True, is_staff=True)

这里可以添加一个函数。例如;如果这个user1不存在,添加user1。

在我的例子中,我们自动使用一些bash, docker, helm,我们有一些问题,转义一些逗号和引号,经过一些尝试/错误后,我们找到了最简单的方法(对我们来说最简单),这个单行命令基于之前共享的文档做到了这一点

DJANGO_SUPERUSER_PASSWORD=12345 DJANGO_SUPERUSER_USERNAME=pacho DJANGO_SUPERUSER_EMAIL=pacho@gmail.com python manage.py createsuperuser --noinput

用shell_plus就简单多了

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

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