Is their any way of counting number of django logins? The last_login field of the auth_user gets updated with each login. Can we make use of that field to count number of logins by a specific user?
+2
A:
Yes, in a sense. You'll need either a field in you app's UserProfile model to hold number of logins or a separate model for storing full login history. Then add signal handlers to listed for last_login updates and record them in a model of your choice. Here's my example:
from django.db import models, signals
from django.contrib.auth.models import User
class UserLogin(models.Model):
"""Represent users' logins, one per record"""
user = models.ForeignKey(user)
timestamp = models.DateTime()
def user_presave(sender, instance, **kwargs):
if instance.last_login:
old = instance.__class__.objects.get(pk=instance.pk)
if instance.last_login != old.last_login:
instance.userlogin_set.create(timestamp=instance.last_login)
signals.pre_save.connect(user_presave, sender=User)
Alex Lebedev
2010-03-26 22:14:46
thanks its working perfectly.
Sujit
2010-03-26 22:42:37
It's a matter of style, but where would you put this in django (what file?). Would you create a new app? Thanks.
Roger
2010-08-15 16:09:30
`UserProfile` goes to `models.py`, signal handler goes to `listeners.py`, both in your main application.
Alex Lebedev
2010-08-16 10:28:57