Add user_id to Google Analytics GTag

This commit is contained in:
Sean Wallace 2020-06-27 12:08:25 -04:00
parent 962af837af
commit 9aa6221b64
3 changed files with 28 additions and 0 deletions

View file

@ -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}');
</script>
"""
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')

View file

@ -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(
'<!-- Google Analytics disabled on internal IP address'), r)
self.assertTrue(r.endswith('-->'), 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)

View file

@ -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`.