Analytics On Laptop

Adding Google Analytics to Django Templates

Adding Google Analytics to Django properly requires a bit of extra steps over just pasting the Google provided JavaScript snippet in your base template and calling it a day. For example, if you use the same analytics key in dev and production you would inadvertently be co-mingling your dev metrics with your production metrics, and in doing so would effectively scramble any useful insights you are trying to extract from your analytics or trends. Instead, the below example shows you how to add Google Analytics to your templates in a way that will work well in split environments.

Assigning The Google Analytics Key

The first step is to add an entry to your project's settings.py file to supply a Google Analytics Key variable from the runtime's environment variables. By and large different environments are delineated by assigning different environment variables depending on the environment (hence the name!). Typically environment variables are given their actual values during the deployment stage (for example creating a Docker container or system-wide settings on the destination server). For the production environment you would set the key provided from the Google Analytics page, for the dev environment you can simple leave this empty as we have added a check for it further down.

 
# settings.py

...

GOOGLE_ANALYTICS_KEY = os.environ.get("GOOGLE_ANALYTICS_KEY")
 

Add A New Template Context Processor

The next step is to add a new Django context processor. The context processor in this case will add the GOOGLE_ANALYTICS_KEY value from settings.py file as a context variable available to all templates processed. The context processor is a minimal function that takes a single HttpRequest parameter and is expected to return a dict.

 
# myapp/context_processors.py

from django.conf import settings
from django.http import HttpRequest


def google_analytics(request: HttpRequest):

    return {
        'GA_KEY': settings.GOOGLE_ANALYTICS_KEY,
    }
 

Enabling The Context Processor

In order for the new context processor to run when each template is processed, it must be defined in the settings.py file under the TEMPLATES > OPTIONS > context_processors section:

 
# settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                ...

                'myapp.context_processors.google_analytics'
            ],
        },
    },
]
 

Adding The JavaScript Snippet

Finally we add the Google provided JavaScript snippet to our base template, with the hard-coded Google Analytics key replaced with the context variable. We also surround the snippet with a check condition so that it isn't include it if GA_KEY is not set, as would be the case if we left it empty in the dev environment:

 


{% if GA_KEY %}
    
    
{% endif %}
 

And that's it! As always you should verify that the resulting pages render as expected by viewing the HTML source output. Good luck and happy coding!