LoginSignup
1
1

More than 1 year has passed since last update.

Djangoのテンプレートでデバッグモードかどうかを判断させる

Posted at

デバッグ判断させるプログラムを作成

アプリケーションディレクトリに、custom_context.pyを作成する。

app/custom_context.py
from django.conf import settings

# HTMLテンプレートでデバッグ判断させられるようにする
def is_debug(request):
    return {"DEBUG": settings.DEBUG}

設定を追加

コンフィグディレクトリのsettings.pyのテンプレート設定部分を編集する。

config/settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / 'templates'
        ],
        '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',
                'base.custom_context.is_debug',    # app/custom_context.py
            ],
        },
    },
]

使い方

settings.pyに記述されているDEBUGの値がHTMLテンプレートに渡されてくる。
これでテンプレートファイルでデバッグモードかどうか判断できるようになった。

template_name.html
{% if DEBUG %}
<!-- This is template_name.html -->
{% endif %}

テンプレートに渡した値を表示しても良いし、ログインしているユーザー名を表示させてもいい。応用次第で色々と使えます。

custom_context.pyは、すべてのHTMLテンプレートに同じデータを渡すことができるので、こちらも応用が効くと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1