diff --git a/analytical/templatetags/google_analytics_gtag.py b/analytical/templatetags/google_analytics_gtag.py index 8b4a2d2..ce9613a 100644 --- a/analytical/templatetags/google_analytics_gtag.py +++ b/analytical/templatetags/google_analytics_gtag.py @@ -10,6 +10,7 @@ from django.template import Library, Node, TemplateSyntaxError from analytical.utils import ( disable_html, + get_identity, get_required_setting, is_internal_ip, ) @@ -22,10 +23,13 @@ SETUP_CODE = """ function gtag(){{dataLayer.push(arguments);}} gtag('js', new Date()); + {extra} gtag('config', '{property_id}'); """ +GTAG_SET_CODE = """gtag('set', {{'{key}': '{value}'}});""" + register = Library() @@ -51,8 +55,18 @@ class GoogleAnalyticsGTagNode(Node): "must be a string looking like 'UA-XXXXXX-Y'") def render(self, context): + other_fields = {} + + identity = get_identity(context) + if identity is not None: + other_fields['user_id'] = identity + + extra = '\n'.join([ + GTAG_SET_CODE.format(key=key, value=value) for key, value in other_fields.items() + ]) html = SETUP_CODE.format( property_id=self.property_id, + extra=extra, ) if is_internal_ip(context, 'GOOGLE_ANALYTICS'): html = disable_html(html, 'Google Analytics') diff --git a/analytical/tests/test_tag_google_analytics_gtag.py b/analytical/tests/test_tag_google_analytics_gtag.py index f1eedd5..1eebe8b 100644 --- a/analytical/tests/test_tag_google_analytics_gtag.py +++ b/analytical/tests/test_tag_google_analytics_gtag.py @@ -2,6 +2,7 @@ Tests for the Google Analytics template tags and filters, using the new gtag.js library. """ +from django.contrib.auth.models import User from django.http import HttpRequest from django.template import Context from django.test.utils import override_settings @@ -50,3 +51,8 @@ class GoogleAnalyticsTagTestCase(TagTestCase): self.assertTrue(r.startswith( ''), r) + + @override_settings(ANALYTICAL_AUTO_IDENTIFY=True) + def test_identify(self): + r = GoogleAnalyticsGTagNode().render(Context({'user': User(username='test')})) + self.assertTrue("gtag('set', {'user_id': 'test'});" in r, r) diff --git a/docs/services/google_analytics_gtag.rst b/docs/services/google_analytics_gtag.rst index 68fb306..5a96a8b 100644 --- a/docs/services/google_analytics_gtag.rst +++ b/docs/services/google_analytics_gtag.rst @@ -81,3 +81,11 @@ setting, the tracking code is commented out. It takes the value of :const:`ANALYTICAL_INTERNAL_IPS` by default (which in turn is :const:`INTERNAL_IPS` by default). See :ref:`identifying-visitors` for important information about detecting the visitor IP address. + +.. _google-analytics-identify-user: + +Identifying authenticated users +------------------------------- + +The username of an authenticated user is passed to Google Analytics +automatically as the `user_id`. See :ref:`identifying-visitors`.