Search code examples
pythondjangotemplates

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.


Solution

  • Assuming you haven't set TEMPLATE_CONTEXT_PROCESSORS to some other value in settings.py, 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 127.0.0.1) 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".