Deploy Google Analytics with Django


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 development instances to contribute to the Google Analytics statistics.

There are a few ways we could deal with this:

  • have a configuration option in which the base template uses to decide whether or not to include the appropriate <script> elements,
  • maintain a branch which we pull into before deploying to the production server, which we ensure includes the <script> elements,
  • do something with Google Analytics to block hits to or localhost, or
  • something else.

The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a google_analytics variable into all of our views?

What are your thoughts?

First, create a way to have your development and production servers pull settings from different files, say and There are lots of ways to do this.

Then, create a setting, GOOGLE_ANALYTICS_KEY. In set it to the empty string. In, 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 %}