このチャプターの目次
カスタムコマンドでスーパーユーザーを作成します。
app フォルダに management フォルダ、commands フォルダを作成し、superuser.py ファイルを作成します。
supeuser のユーザーが存在しない場合に、作成するようにしています。
もしデプロイと同時に実行したいコマンドがある場合は、このように作成してください。
app/management/commands/superuser.py
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.conf import settings
User = get_user_model()
class Command(BaseCommand):
def handle(self, *args, **options):
if not User.objects.filter(username=settings.SUPERUSER_NAME).exists():
User.objects.create_superuser(
username=settings.SUPERUSER_NAME,
email=settings.SUPERUSER_EMAIL,
password=settings.SUPERUSER_PASSWORD
)
print("スーパーユーザー作成")
動作確認
カスタムコマンドでスーパーユーザーが作成できるか確認しましょう。
python3 manage.py superuser
Django 管理画面にスーパーユーザーでログインできたら成功です。