Deploying Google Analytics With Django

19,549

Solution 1

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

Solution 2

A little late to the party, but there's a reusable Django app called django-google-analytics. The easiest way to use it is:

  1. Add the google_analytics application to your INSTALLED_APPS section of your settings.py.
  2. In your base template, usually a base.html, insert this tag at the very top: {% load analytics %}
  3. In the same template, insert the following code right before the closing body tag: {% analytics "UA-xxxxxx-x" %} the UA-xxxxxx-x is a unique Google Analytics code for your domain.

Solution 3

My solution takes a similar approach to Ned's preferred answer, but separates the analytics code into its own template. I prefer this, so I can just copy the template from project to project.

Here's a snippet from my context_processor file:

from django.conf import settings
from django.template.loader import render_to_string

def analytics(request):
    """
    Returns analytics code.
    """
    if not settings.DEBUG:
        return { 'analytics_code': render_to_string("analytics/analytics.html", { 'google_analytics_key: settings.GOOGLE_ANALYTICS_KEY }) }
    else:
        return { 'analytics_code': "" }

Of course you'll need to tell Django to include this in your context. In in your settings.py file, include:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "context_processors.analytics",
)

I have it set up to include the analytics code only when DEBUG is set to False, but you may prefer to key it off something else, perhaps a new setting altogether. I think DEBUG is a good default since it supposes you don't want to track any hits while debugging/developing.

Create a setting with your Google Analytics Key:

GOOGLE_ANALYTICS_KEY = "UA-1234567-8"

Create a template called: "analytics/analytics.html" that includes something like this:

<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("{{ google_analytics_key }}");
pageTracker._trackPageview();
} catch(err) {}</script>

Finally, just before the closing tag in your base.html template, add this:

{{ analytics_code }}

Now your analytics code will be included only when DEBUG=False. Otherwise, nothing will be included.

Solution 4

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

  1. this doesn't work with realtime filtering, because no filters are applied to realtime (as of July 2012--check their documents)
  2. you have to be an admin with the Google Analytics account to set this up

Solution 5

Another simple way. In settings.py,Check debug is True, then add:

INTERNAL_IPS = (
    '127.0.0.1',
    'localhost',
)

Then you can use things in your template like this:

{% if not debug %}
<script> blah blah </script>
{% endif %}

If want to change to production, set debug to False.

Ref: http://www.djangobook.com/en/2.0/chapter09.html

Share:
19,549
Lavaman65
Author by

Lavaman65

A cloud software engineer for Canonical, and general Python hacker.

Updated on June 18, 2022

Comments

  • Lavaman65
    Lavaman65 almost 2 years

    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 settings.py 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 127.0.0.1 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?