[Django] allauthのtemplatesのHTMLをカスタマイズする方法

目次

前提

以下の記事の内容を先に完了している必要がある。

  1. 最も基本的なdjango-allauthを使用したログイン機能
  2. DjangoでCustomUser+allauthを使用した認証

Templateファイルをコピー

テンプレート用ディレクトリを作成。
※任意のため注意

mkdir template/custom_auth

テンプレートファイルをコピーする。
Pythonバージョンに注意すること。※今回の手順ではPythonの3.8となっている。

cd /usr/local/lib/python3.8/site-packages/allauth/templates/
cp -rp * /code/templates/custom_auth/.

Settting.pyの修正

TEMPLATE.DIRSにPath.joinpath(BASE_DIR, ‘templates’, ‘custom_auth’),を追記。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            Path.joinpath(BASE_DIR, 'templates'),
            Path.joinpath(BASE_DIR, 'templates', 'custom_auth'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

HTMLファイルの修正

template/custom_auth/account配下のHTMLファイルを修正

 解説

  • Djangoの仕様は最初にTEMPLATES.DIR指定のPATH配下からtemplateのHTMLファイルを検索していく。
  • 次に/usr/local/lib/pythonX.X/site-packages/allauth/templatesの配下のtemplateのHTMLファイルを検索する
  • Djangoは先に条件に合致したtemplateファイルを使用する。
  • 今回の場合、template/custom_authが/usr/local/lib/python3.8/site-packages/allauth/templatesよりも優先されているためHTMLファイルを変更できる
  • 直接/usr/local/lib/pythonX.X/site-packages/allauth/templatesのファイルも修正出来るが、バージョンアップ時にdegradeする。

参考

よかったらシェアしてね!
  • URLをコピーしました!
目次