In today’s data-driven world, understanding how visitors interact with your website is essential. Google Analytics (GA) provides deep insights into traffic, behavior, and conversions. If you’re running a Django-based CMS, integrating Google Analytics directly into your system will allow site staff to view analytics without leaving the CMS dashboard.
In this guide, we’ll cover how to:
- Set up Google Analytics for your Django site
- Add the GA tracking code to your templates
- Use the Google Analytics Reporting API to pull analytics data
- Build a Django admin/staff dashboard to view site analytics
1. Prerequisites
Before we dive in, make sure you have:
- A working Django project (CMS or custom-built)
- Google Analytics 4 (GA4) property created for your site
- Python 3.8+
- A service account with API credentials from Google Cloud
2. Adding Google Analytics Tracking to Django Templates
The simplest way to start collecting data is by embedding the Google Analytics tracking snippet inside your Django base template.
In your GA dashboard, go to Admin → Data Streams → Web → Tagging Instructions and copy the gtag.js snippet.
For example, in base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Your existing meta tags -->
<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'); <!-- Replace with your Measurement ID -->
</script>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Once deployed, Google Analytics will start tracking visitors.
3. Setting Up Google Analytics API Access
To show analytics data to your staff inside the Django CMS, you’ll need API access.
- Go to Google Cloud Console → Create a new project.
- Enable the Google Analytics Data API.
- Create a Service Account and download the JSON key file.
- Share your GA property with this service account email under Account → Property Access Management.
4. Install Dependencies
Install Google’s Python client library:
pip install google-analytics-data
5. Fetching Analytics Data in Django
Let’s create a Django service that queries GA for page views, users, and sessions.
In analytics/services.py:
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import DateRange, Metric, Dimension, RunReportRequest
import os
GA_PROPERTY_ID = "YOUR_GA4_PROPERTY_ID"
GA_CREDENTIALS = "path/to/credentials.json"
def get_ga_report():
client = BetaAnalyticsDataClient.from_service_account_file(GA_CREDENTIALS)
request = RunReportRequest(
property=f"properties/{GA_PROPERTY_ID}",
dimensions=[Dimension(name="pagePath")],
metrics=[Metric(name="screenPageViews"), Metric(name="activeUsers")],
date_ranges=[DateRange(start_date="7daysAgo", end_date="today")],
)
response = client.run_report(request)
results = []
for row in response.rows:
results.append({
"page": row.dimension_values[0].value,
"views": row.metric_values[0].value,
"users": row.metric_values[1].value,
})
return results
6. Creating a Django View & Template
In analytics/views.py:
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render
from .services import get_ga_report
@staff_member_required def analytics_dashboard(request):
data = get_ga_report()
return render(request, "analytics/dashboard.html", {"report": data})
In analytics/urls.py:
from django.urls import path
from .views import analytics_dashboard
urlpatterns = [
path("dashboard/", analytics_dashboard, name="analytics_dashboard"),
]
7. Template for Staff Dashboard
Create analytics/templates/analytics/dashboard.html:
{% extends "base.html" %}
{% block content %}
<h2>Google Analytics Dashboard</h2>
<table border="1" cellpadding="5">
<tr>
<th>Page</th>
<th>Views</th>
<th>Users</th>
</tr>
{% for row in report %}
<tr>
<td>{{ row.page }}</td>
<td>{{ row.views }}</td>
<td>{{ row.users }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Now, staff can log in to the Django CMS and view live site analytics without leaving the admin.
8. Enhancements
- Add charts using Chart.js for better visualization.
- Cache results with Django cache or Celery to reduce API calls.
- Restrict analytics access to specific staff groups.
- Extend to include metrics like bounce rate, average session duration, top referrers.
Conclusion
By integrating Google Analytics directly into your Django CMS, you empower your staff with actionable insights without requiring them to log into the GA dashboard separately. This streamlined workflow not only improves efficiency but also helps content editors and managers make smarter, data-backed decisions.
👉 Next Step: Add Chart.js graphs and real-time reporting for a more professional analytics dashboard.