1

I implemented Segment.io in my Django application. Once the user logs in I have to call analytics.identify once.

Currently, I call it every time on every page load as long {% if user.is_authenticated %} is the case. Do you have any idea how I can only call it once after the user logged in?

<script type="text/javascript">
  {% if user.is_authenticated %}
    analytics.identify('{{ user.email }}', {
      'first_name': user.first_name,
      'last_name': user.last_name,
    });
  {% endif %}
</script>
blhsing
  • 91,368
  • 6
  • 71
  • 106
Joey Coder
  • 3,199
  • 8
  • 28
  • 60

3 Answers3

1

The way I would implement this is:

  • Change your 'login' view (the one that calls authenticate and login) to return a page, rather than a redirect.
  • This page would have the script tag you've mentioned above, as well as a meta refresh redirect to the main page (or wherever you want the user to go)
Shadow
  • 8,749
  • 4
  • 47
  • 57
0

You can set a cookie in your response object so that in the next page load you can avoid rendering the call to analytics.identify if that cookie is set:

def view(request):
    template = loader.get_template('polls/index.html')
    context = {'user_unidentified': 'user_identified' not in request.COOKIES}
    response = HttpResponse(template.render(context, request))
    if 'user_identified' not in request.COOKIES:
        response.set_cookie('user_identified', '1')
    return response

Then in your template:

<script type="text/javascript">
  {% if user_unidentified %}
    analytics.identify('{{ user.email }}', {
      'first_name': user.first_name,
      'last_name': user.last_name,
    });
  {% endif %}
</script>
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

You can use django signals for this. Put this code in your models.

from django.contrib.auth.signals import user_logged_in

def do_stuff(sender, user, request, **kwargs):
    whatever...

user_logged_in.connect(do_stuff)

for more information, check out https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals and http://docs.djangoproject.com/en/dev/topics/signals/

Original Answer: https://stackoverflow.com/a/6109366/4349666

Manish Gupta
  • 4,438
  • 18
  • 57
  • 104