How to test if debug is true or false in a template with django ?

Published: May 29, 2019

DMCA.com Protection Status

Examples of how to test if debug is true or false in a template with django:

Approach 1

If only few templates are going to use the flag DEBUG a simple solution is to do in the file views.py:

from django.conf import settings

def my_view(request):
    debug_flag = settings.DEBUG
    context = {'debug_flag':debug_flag}
    return render(request, "my_app/my_template.html", context )

We can then use the debug flag in the template "my_template.html":

{% if debug_flag %}
    do something
{% else %}
    do something
{% endif %}

Approach 2

Another solution is to use a context processor to access the debug value in any template. For that, just add in the pro
processor.py file:

from django.conf import settings

def my_context(request):
    debug_flag = settings.DEBUG
    return{"debug_flag":debug_flag}

and in the settings.py file the following line 'my_app.processor.my_context':

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
                'my_app.processor.my_context',
            ],
        },
    },
]

It is then possible to check the debug value in any template:

{% if debug_flag %}
    do something
{% else %}
    do something
{% endif %}

Approach 3

Another solution is to use INTERNAL_IPS in the file settings.py:

INTERNAL_IPS = (
    '127.0.0.1',
)

and then do in a template:

{% if debug %}
    do something
{% else %}
    do something
{% endif %}

References