Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 369
luc Avatar asked Aug 13 '09 12:08

luc


People also ask

How do I change the flag in Django?

To use Django-Flags you first need to define the flag, use the flag, and define conditions for the flag to be enabled. Then visiting the URL /mypage? enable_my_flag=True should show you the flagged <div> in the template.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What is Autoescape in Django template?

autoescape. Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.


3 Answers

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".

like image 132
mipadi Avatar answered Oct 16 '22 08:10

mipadi


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

in myapp/context_processors.py:

from django.conf import settings

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

in settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'myapp.context_processors.debug',
)

Then in my templates, simply:

 {% if DEBUG %} .header { background:#f00; } {% endif %}
like image 26
fredley Avatar answered Oct 16 '22 07:10

fredley


Django 1.9+

settings.py:

INTERNAL_IPS = (
    '127.0.0.1',
)

Templates:

{% if debug %}

https://docs.djangoproject.com/en/dev/ref/settings/#internal-ips says:

A list of IP addresses, as strings, that:

  • Allow the debug() context processor to add some variables to the template context.

The debug context processor is in the default settings.py.