我是 Django 的新手。我的 django 应用程序在 docker 中运行,我需要创建一个 super 用户而不使用 createsuperuser 命令我尝试使用此代码 initadmin.py (如下所示),但我无法使用“python manage.py 在 bash 文件中运行它初始化管理”。它不起作用!
initadmin.py:
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
def handle(self, *args, **options):
if User.objects.count() == 0:
for user in settings.ADMINS:
username = 'admin'
email = 'admin.com'
password = 'admin'
print('Creating account for %s (%s)' % (username, email))
admin = User.objects.create_superuser(email=email, username=username, password=password)
admin.is_active = True
admin.is_admin = True
admin.save()
else:
print('Admin accounts can only be initialized if no Accounts exist')
谁能告诉我我做错了什么?有更好的方法以编程方式创建 super 用户吗?
最佳答案
这是create_superuser
的定义:
请注意,
其实你可以改变顺序,我刚刚试过了。用户名
、电子邮件
、密码
不是关键字参数,调用此方法时无法更改顺序。
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, email, password, **extra_fields)
只需在代码中执行此操作即可:
User.objects.create_superuser(username, email, password)
is_admin
不是默认用户模型的属性,您的意思是is_staff
吗?
无论如何,您不需要设置这些,因为 create_superuser
会为您设置它们。
您也不需要调用 save
。
PROJECT_ROOT/
YOUR_APP/
__init__.py
models.py
management/
commands/
initadmin.py
tests.py
views.py
关于python - 如何在不使用manage.py createsuperuser命令的情况下以编程方式在docker中为django创建 super 用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642809/