from django.contrib.auth.management.commands import createsuperuser
from django.core.management import CommandError
class Command(createsuperuser.Command):
help = 'Crate a superuser, and allow password to be provided'
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
'--password', dest='password', default=None,
help='Specifies the password for the superuser.',
)
def handle(self, *args, **options):
password = options.get('password')
username = options.get('username')
database = options.get('database')
if password and not username:
raise CommandError("--username is required if specifying --password")
super(Command, self).handle(*args, **options)
if password:
user = self.UserModel._default_manager.db_manager(database).get(username=username)
user.set_password(password)
user.save()
if [[ -n "$CREATE_SUPER_USER" ]]; then
echo "==> Creating super user"
cd /app/example_project/src
printf "from django.contrib.auth.models import User\nif not User.objects.exists(): User.objects.create_superuser(*'$CREATE_SUPER_USER'.split(':'))" | python /app/example_project/manage.py shell
fi
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),
]
希望有帮助!
< p > 编辑:
有些人可能会提出这样的问题:如何设置这些环境变量并让Django知道它们。有很多方法,在其他SO帖子中已经回答过,但只是作为一个快速指针,创建.env文件是一个好主意。然后你可以使用python-dotenv包,但如果你已经用pipenv设置了一个虚拟环境,它会自动在你的.env文件中设置envars。同样地,通过docker-compose运行你的应用程序可以读取你的.env文件
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()
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 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.
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)