[英]Django: Call function once on login
I implemented Segment.io in my Django application.我在我的 Django 应用程序中实现了 Segment.io。 Once the user logs in I have to call analytics.identify
once.用户登录后,我必须调用analytics.identify
一次。
Currently, I call it every time on every page load as long {% if user.is_authenticated %}
is the case.目前,我每次在每次加载页面时都调用它,只要{% if user.is_authenticated %}
是这种情况。 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>
The way I would implement this is:我将实现这一点的方式是:
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:您可以在您的响应对象中设置一个 cookie,以便在下一个页面加载中,如果设置了该 cookie,您可以避免呈现对analytics.identify
的调用:
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>
You can use django signals for this.您可以为此使用 django 信号。 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/有关更多信息,请查看https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals和http://docs.djangoproject.com/en/dev /主题/信号/
Original Answer: https://stackoverflow.com/a/6109366/4349666原答案: https : //stackoverflow.com/a/6109366/4349666
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.