如果 Django 超级用户不以非交互方式存在,如何创建它?

How to create a Django superuser if it doesn't exist non-interactively?

我想通过 Bash 脚本自动创建 Django 用户。我发现这个片段几乎符合我的需要:

echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')" |\
    python manage.py shell

如果用户已经存在,我如何修改它以使其成为 nop?

您可以使用 get_or_create()。如果它存在它什么都不做,否则它会创建一个。

您必须手动将 is_staffis_superuser 设置为 True

使用manage.py shell

您可以使用 QuerySet API 方法来检查用户是否存在,如果不存在则创建它。另外,将代码放在 heredoc 中可能更容易:

cat <<EOF | python manage.py shell
from django.contrib.auth import get_user_model

User = get_user_model()  # get the currently active user model,

User.objects.filter(username='admin').exists() or \
    User.objects.create_superuser('admin', 'admin@example.com', 'pass')
EOF

使用自定义管理命令

另一个更易于维护的选项是为您的 Django 应用程序添加自定义 management command。改编文档中的示例,将 yourapp/management/commands/ensure_adminuser.py 编辑为如下所示:

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "Creates an admin user non-interactively if it doesn't exist"

    def add_arguments(self, parser):
        parser.add_argument('--username', help="Admin's username")
        parser.add_argument('--email', help="Admin's email")
        parser.add_argument('--password', help="Admin's password")

    def handle(self, *args, **options):
        User = get_user_model()
        if not User.objects.filter(username=options['username']).exists():
            User.objects.create_superuser(username=options['username'],
                                          email=options['email'],
                                          password=options['password'])

然后您可以从 Bash 脚本中调用新的自定义命令,如下所示:

python manage.py ensure_adminuser --username=admin \
    --email=admin@example.com \
    --password=pass

这个 bash 函数可以解决问题,即使您的应用程序中有自定义用户模型也是如此:

create-superuser () {
    local username=""
    local email=""
    local password=""
    cat <<EOF | python manage.py shell
from django.contrib.auth import get_user_model

User = get_user_model()

if not User.objects.filter(username="$username").exists():
    User.objects.create_superuser("$username", "$email", "$password")
else:
    print('User "{}" exists already, not created'.format("$username"))
EOF
}

感谢 Eugene Yarmash 的原创想法。