We\'re about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don\'t want all of the hits on developmen
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this.
Then, create a setting, GOOGLE_ANALYTICS_KEY
. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a context processor to add this setting to all your template contexts, either as GOOGLE_ANALYTICS_KEY
, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code:
{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
I mostly agree with Ned, although I have a single setting called IS_LIVE_SITE which toggles analytics code, adverts and a few other things. This way I can keep all the keys in subversion (as it is a pain to look them up) and still toggle them on or off easily.
All of these other solutions may work, but they are all overkill now because you can easily set up a filter in Google Analytics to filter out all traffic that is not coming from your production website or websites. See Create/Manage Profile Filters in the GA Help. A solution with no code just makes everybody's life easier.
Note: there are two caveats
You have template context processors that can be used to pass values to all templates without updating all your views.
http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors