简体   繁体   中英

Google Analytics User-ID returning Uncaught ReferenceError: None is not defined when user is not logged | Python

I am setting up the code for GA User-ID on my Python template (head section). The full GA script is:

<!-- Google Analytics -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-HIDDENFORTHISQUESTION-1', 'auto');
  ga('set', '&uid', {{ request.user.id }});
  ga('send', 'pageview');
</script>

I get this error when resquest.user.id is set to None, as no user is logged in on the site:

ga('set', '&uid', None);

When a user is logged in, I get the proper id number and no error (eg 8543 stands for registered user #8543):

ga('set', '&uid', 8543);

How can I avoid this error when user.id returns None?

I believe I should wrap that line in an if sentence to convert the value "None" into NULL or 0, but my JS is very limited and I don't want to mess anything up :)

Thanks in advance for your help!

None is not a name of a function so it emits an Error.

Make condition in your Python macro:

if('{{request.user.id}}'!='None') {
  ga('set', '&uid', {{request.user.id}});
  }

PS: I dont know python, so the syntax is nonsense, but you know and this will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM