views:

344

answers:

3

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.

A: 

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.

Lakshman Prasad
+2  A: 

Assuming you haven't set TEMPLATE_CONTEXT_PREPROCESSORS 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".

mipadi
It seems to correspond to my need but unfortunately it doesn't work for me. I can't find what is wrong.
luc
That works perfectly as long a I use a RequestContext rather than a Context. Thanks a lot!
luc
Oops, sorry! I did forget to mention that you have to pass a `RequestContext` to the template.
mipadi
How do you check for it in the template? According to the docs, ifequal is insufficient:It is only possible to compare an argument to template variables or strings. You cannot check for equality with Python objects such as True or False. If you need to test if something is true or false, use the if tag instead.However, {% if %} doesn't work. It checks existence, not whether it's True or False.
Wilhelm
The `if` tag *should* work. From the Django docs: "The `{% if %}` tag evaluates a variable, and if that variable is 'true' (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output."
mipadi
+2  A: 

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.

rizumu