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


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



This means the root domain you registered in Google Analytics. Even if you are configuring a subdomain (e.g. or you must use the root domain. For instance,


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:



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:

  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

  ga('send', 'pageview');


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!):

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