Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

djangoで、createsuperuserコマンドを作成して、Dockerfileで実行する。

概要

python, djangoで、createsuperuserコマンドを作成する

参考サイト

realpython.com

アクションを自作する — Django 1.4 documentation

やってみたこと

  • コマンドのコードを実行するファイルを作成する。
  • Dockerfileで実行する。

コマンドのコードを実行するファイルを作成する。

  • managementフォルダ-commandsフォルダ-実行ファイル.pyを作成する。
-website
└─ management
    ├── __init__.py
    └── commands
        ├── __init__.py
        └── createsu.py

この時に、websiteをINSTALLED_APPSに登録していないと、読み込まれないので、注意!

  • createsu.pyのコードを作成する。
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User


class Command(BaseCommand):

    def handle(self, *args, **options):
        if not User.objects.filter(username="[adminuserのユーザー名]").exists():
            User.objects.create_superuser("[user名]", "[mail]", "[password]")

これで、python manage.py createsu というコマンドが使えるようになる!

Dockerfileに実行するコマンドを追記する。

# こういう感じ
RUN python /home/docker/code/app/manage.py createsu

これで無事createsuコマンドが使えるようになった!