Implement Google Analytics such that it only runs on the production domain and is disabled on localhost.
Configuration
.env
# Google Analytics
GOOGLE_ANALYTICS_ID=G-XXXXXXXXXXbase.py
Load GOOGLE_ANALYTICS_ID from environment variables.
Add yourapp.context_processors.google_analytics to TEMPLATES['OPTIONS']
# Google Analytics Settings GOOGLE_ANALYTICS_ID = os.getenv('GOOGLE_ANALYTICS_ID', '')
context_processors.py
from django.conf import settings def google_analytics(request): """ Context processor to add Google Analytics ID to the context. Only returns the ID if the current host is not localhost or 127.0.0.1. """ ga_id = getattr(settings, 'GOOGLE_ANALYTICS_ID', None) host = request.get_host().split(':')[0].lower() # Check if host is localhost or 127.0.0.1 if host in ['localhost', '127.0.0.1']: return {'GOOGLE_ANALYTICS_ID': None} return {'GOOGLE_ANALYTICS_ID': ga_id}
base.html
Add the Google Analytics global site tag (gtag.js) inside the <head> section
{% if GOOGLE_ANALYTICS_ID %} <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script> {% endif %}
, wrapped in an {% if GOOGLE_ANALYTICS_ID %} block.
{% if GOOGLE_ANALYTICS_ID %} <!-- Global site tag (gtag.js) - Google Analytics --> <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> {% endif %}