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

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


当前回答

我建议运行一个数据迁移,这样当迁移应用到项目中时,超级用户将作为迁移的一部分被创建。用户名和密码可以设置为环境变量。这在容器中运行应用程序时也很有用(以这个线程为例)。

您的数据迁移将看起来像这样:

import os
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('<your_app>', '<previous_migration>'),
    ] # can also be emtpy if it's your first migration

    def generate_superuser(apps, schema_editor):
        from django.contrib.auth.models import User

        DJANGO_SU_NAME = os.environ.get('DJANGO_SU_NAME')
        DJANGO_SU_EMAIL = os.environ.get('DJANGO_SU_EMAIL')
        DJANGO_SU_PASSWORD = os.environ.get('DJANGO_SU_PASSWORD')

        superuser = User.objects.create_superuser(
            username=DJANGO_SU_NAME,
            email=DJANGO_SU_EMAIL,
            password=DJANGO_SU_PASSWORD)

        superuser.save()

    operations = [
        migrations.RunPython(generate_superuser),
    ]

希望有帮助!

编辑: 有些人可能会提出这样的问题:如何设置这些环境变量并让Django知道它们。有很多方法,在其他SO帖子中已经回答过了,但是作为一个快速的指针,创建一个.env文件是一个好主意。然后您可以使用python-dotenv包,但是如果您已经使用pipenv设置了一个虚拟环境,它将自动在您的.env文件中设置envars。同样地,通过docker-compose运行你的应用程序可以读取你的.env文件。

其他回答

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中,你可以通过环境变量来传递凭证。然而,这种方法更加灵活,因为它允许您执行任何其他更复杂的任务,如删除所有测试用户等。

我使用了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"
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
        )

你可以像这样在自定义命令中创建一个超级用户:

import os

from django.contrib.auth.models import User
from django.core.management import BaseCommand, call_command

from immo_project import settings


class Command(BaseCommand):
    def handle(self, *args, **options):
        call_command('createsuperuser', interactive=False, username='admin', email='test@example.com')
        user = User.objects.get(username='admin')
        user.set_password('password')
        user.save()