How to check the TEMPLATE_DEBUG flag in a django template?


Do you know if it is possible to know in a django template if the TEMPLATE_DEBUG flag is set?

I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.

For sure, I can add this flag to the context but I would like to know if there is a better way to do that.

12/7/2009 5:49:37 AM

Accepted Answer

Assuming you haven't set TEMPLATE_CONTEXT_PROCESSORS to some other value in, Django will automatically load the debug context preprocessor (as noted here). This means that you will have access to a variable called debug in your templates if settings.DEBUG is true and your local machine's IP address (which can simply be is set in the variable settings.INTERNAL_IPS (which is described here). settings.INTERNAL_IPS is a tuple or list of IP addresses that Django should recognize as "internal".

9/29/2017 2:38:59 PM

If modifying INTERNAL_IPS is not possible/suitable, you can do this with a context processor:

in myapp/

from django.conf import settings

def debug(context):
  return {'DEBUG': settings.DEBUG}



Then in my templates, simply:

 {% if DEBUG %} .header { background:#f00; } {% endif %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow