Home » Django » How to check the TEMPLATE_DEBUG flag in a django template?

How to check the TEMPLATE_DEBUG flag in a django template?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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.

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

Questions:
Answers:

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 %}

Questions:
Answers:

Django 1.9 settings.py:

INTERNAL_IPS = (
    '127.0.0.1',
)

Templates:

{% if debug %}

https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-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.

Questions:
Answers:

If you haven’t already, it always helps to see if/how others have dealt with same issue on djangosnippets. The most recent snippet working with analytics tag is 1656:
http://www.djangosnippets.org/snippets/1656/

What is nice about this solution is that it allows you to keep your GOOGLE_ANALYTICS_CODE = xxxxxx in local_settings.py in the case rest of your source is public, your key remains private. In addition it goes an extra step to not use analytics for logged in users.

Includes the Javascript for Google Analytics. Will not show Google Analytics code when DEBUG is on or to staff users.

Use {% googleanalyticsjs %} in your templates.

You must set something like

GOOGLE_ANALYTICS_CODE = "UA-1234567-1"

in your settings file.

Assumes ‘user’ in your template variables is request.user, which it will be if you use:

return render_to_response('template.html',{ }, context_instance=RequestContext(request))

(Assuming django.core.context_processors.auth is in TEMPLATE_CONTEXT_PROCESSORS, which it is by default)


from django import template
import settings
register = template.Library()


class ShowGoogleAnalyticsJS(template.Node):
  def render(self, context):
      code =  getattr(settings, "GOOGLE_ANALYTICS_CODE", False)
      if not code:
          return "<!-- Goggle Analytics not included because you haven't set the settings.GOOGLE_ANALYTICS_CODE variable! -->"

      if 'user' in context and context['user'] and context['user'].is_staff:
          return "<!-- Goggle Analytics not included because you are a staff user! -->"

      if settings.DEBUG:
          return "<!-- Goggle Analytics not included because you are in Debug mode! -->"

      return """
      <script type="text/javascript">
          var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
          document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'
            type='text/javascript'%3E%3C/script%3E"));
      </script>
      <script type="text/javascript">
          try {
          var pageTracker = _gat._getTracker('""" + str(code) + """');
          pageTracker._trackPageview();
      } catch(err) {}</script>
      """

def googleanalyticsjs(parser, token):
  return ShowGoogleAnalyticsJS()

show_common_data = register.tag(googleanalyticsjs)
Questions:
Answers:

{% if debug %} can do the trick but only if you pass RequestContext instead of Context. Additionally, debug is not a boolean flag, its a function that when evaluated while DEBUG = True return some debugging information. This can be unnecessary overhead for your template.

Personally, I do this trick instead.

{% if request.META.HTTP_HOST == "127.0.0.1:8000" %}

This will always work but instead of relying on both DEBUG flag and INTERNAL_IP, it just work for the hard coded IP.

Questions:
Answers:

You will need to add the DEBUG flag to your context_processors.

There may not even be an alternative way. At least, none that I know of.