Django: How to get the first time a user logged in within 24 hours in django
In Django, we can get the time a user last logged in by using Auth.User.last_login. That is only updated when the user logs in using his username/password.
This would be useful for queries such as getting the number of new records since the last visit.
Users can log out and also login multiple times in a day, now I want to get the first time a user logged in, in a day and store it in a model in the db.
How do I achieve this functionality?
Your last_login field only holds a single point of data, i.e. the last time that a login occurred - if someone logs in twice in a day, you won't be able to see that first login by the time the second one occurs. You would therefore need to create some sort of log model that tracks when logins occur, you can then filter that quite easily to get first login of the day:
class UserActivity(models.Model):
activity_type = # track whether logged in, logged out, etc.
created_on = models.DateTimeField(...
You will need to put this with your login code so that an activity is always created when the login is successful. Then you can get the first login like so:
first_login_today = user.useractivity_set.filter(
created_on__date=timezone.now().date()).first()