Creating a pluggable Django app to just embed the GA code seemed overkill to me, so I created this post as a quick reference for next Django web projects.

The idea is creating a system that will add the tracking code under the following conditions:

  • We have provided the ID and domain of our GA configuration.
  • We are not running in settings.DEBUG mode.

Settings variables

The following settings must be defined on your settings.py.

GOOGLE_ANALYTICS_PROPERTY_ID

A string containing your ID on GA (e.g. UA-14845987-3). Get it from your configuration page:

GOOGLE_ANALYTICS_PROPERTY_ID = 'UA-14845987-3'

GOOGLE_ANALYTICS_DOMAIN

This means the root domain you registered in Google Analytics. Even if you are configuring a subdomain (e.g. www.mydoamin.com or foo.mydomain.com) you must use the root domain. For instance, mydomain.com:

GOOGLE_ANALYTICS_DOMAIN = 'mydomain.com'

Context Processor

Add this function to your context processors file:

from django.conf import settings

def google_analytics(request):
    """
    Use the variables returned in this function to
    render your Google Analytics tracking code template.
    """
    ga_prop_id = getattr(settings, 'GOOGLE_ANALYTICS_PROPERTY_ID', False)
    ga_domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', False)
    if not settings.DEBUG and ga_prop_id and ga_domain:
        return {
            'GOOGLE_ANALYTICS_PROPERTY_ID': ga_prop_id,
            'GOOGLE_ANALYTICS_DOMAIN': ga_domain,
        }
    return {}

Add the context processor to your settings:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'website.context_processors.google_analytics',
)

Template

It will contain the tracking code that Analytics prodide you in order to start receiving data. Notice that the are substituting the ID and domain with our two GOOGLE_ANALYTICS_PROPERTY_ID and GOOGLE_ANALYTICS_DOMAIN setting vars. Create the template (I use to name it ga.html) somewhere your project can find it:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', '{{ GOOGLE_ANALYTICS_PROPERTY_ID }}', '{{ GOOGLE_ANALYTICS_DOMAIN }}');
  ga('send', 'pageview');

</script>

NOTE: I am using the new analytics.js snippet here, which is currently in public beta. You can replace this code above with the traditional snippet (called ga.js). In fact, you can embed both of them, as stated in the link.

Finally, we want to load the tracking code at any point into our HTML, so go edit your base.html equivalent and add something like this to include the template only if GOOGLE_ANALYTICS_PROPERTY_ID exists with some value on our configuration (replace the path with your own one!):

{% if GOOGLE_ANALYTICS_PROPERTY_ID %}
  {% include "path/to/your/ga.html" %}
{% endif %}