【Django】カスタム User モデルの作成方法

Django プロジェクトを作る際、もしデフォルトの User モデルで機能が足りている場合でも、将来の保守性や変更の必要性が出た場合を考慮して、カスタムの User モデルを使用することが強く推奨されています。

また、この作業 Django プロジェクトを作成して最初の migrate 実行前に行う必要があります。

  1. ユーザー管理用アプリケーションの作成
  2. カスタム User モデルの作成
  3. カスタム User モデルの登録
  4. マイグレーション

参考資料

ユーザー管理用アプリケーションの作成

account という名前でアプリケーションを作ります。

% python manage.py startapp account
# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'account.apps.AccountConfig', # 追記
]

カスタム User モデルの作成

# account/models.py

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

カスタム User モデルの登録

# settings.py

AUTH_USER_MODEL = 'account.User'

尚、この設定をした時の注意点として、django.contrib.auth.models の User を直接参照すると AUTH_USER_MODEL で設定した User モデルを参照できないそうです。

なので User モデルを参照する必要がある場合は django.contrib.auth.get_user_model() を使用する必要があります。

# account/admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User # models.py のカスタム User をインポート

admin.site.register(User, UserAdmin)

マイグレーション

まず、新たに作成した「account」アプリケーションのマイグレーションを作成します。

% python manage.py makemigrations account
Migrations for 'account':
  account/migrations/0001_initial.py
    - Create model User

マイグレーションを実行します。

% python manage.py migrate
Operations to perform:
  Apply all migrations: account, admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying account.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying sessions.0001_initial... OK

無事マイグレーション完了です。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です