How to Add Google Analytics to Your Django Blog
Google Analytics helps you track and understand your website traffic. In this guide, we’ll walk through how to integrate Google Analytics into a Django-powered blog by adding the tracking script to your templates.
Google Analytics helps you track and understand your website traffic. In this guide, we’ll walk through how to integrate Google Analytics into a Django-powered blog by adding the tracking script to your templates.
Steps to Add Google Analytics to Your Blog
- Create a Google Analytics Account
Go to Google Analytics and sign in with your Google account. Click “Start measuring” and follow the steps to set up an account, a property, and a data stream (select Web).
- Copy the Global Site Tag (gtag.js)
After creating the data stream, you will get a snippet of code that looks like this:
`
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
`
Replace G-XXXXXXXXXX with your actual Google Analytics Measurement ID.
- Edit Your Django Template
Open your base template (commonly base.html) and paste the tracking code inside the <head> section:
`
<!DOCTYPE html>
<html lang="en">
<head>
...
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
...
</head>
<body>
...
</body>
</html>
`
- Optional: Use Django Settings for Dynamic ID
If you want to avoid hardcoding the ID, pass it from your Django settings:
- Add to
settings.py:
`GOOGLE_ANALYTICS_ID = "G-XXXXXXXXXX"`
- Create a context processor to expose it to templates:
`
# context_processors.py
def analytics_id(request):
from django.conf import settings
return {'GOOGLE_ANALYTICS_ID': settings.GOOGLE_ANALYTICS_ID}
`
Register the context processor in TEMPLATES settings.
- In your Django base template:
`
<script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ GOOGLE_ANALYTICS_ID }}');
</script>
`
- Deploy and Verify
Deploy your blog and visit it in a browser. Open Google Analytics and check the Realtime report to verify tracking is working.
Tip: For privacy compliance, especially under GDPR, consider showing a cookie consent banner before loading Google Analytics.