Alireza Ghaffari
Alireza Ghaffari

Reputation: 1104

how to count how many times a user logs in?

I want to have a detail statistics about each of my site's user How can I count how many times each user logs in?

Python.V=3.4 Django.V=1.7

In my models.py

I just extended the users' model:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    age = models.IntegerField(max_length=2, blank=True, validators=[MinValueValidator(3), MaxValueValidator(99)])
    birth_day = models.DateField(default=date(2015, 1, 1))
    location = models.CharField(max_length=300, blank=True)
    gender = models.CharField(max_length=1, choices=SEX, default='N')
    about_me = models.CharField(max_length=40, blank=True)
    #other fields here

    def __str__(self):
        return "%s's profile" % self.user

Upvotes: 2

Views: 3004

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52173

You can add a new field to UserProfile model to store the number of successful logins of the user and then, listen for user_logged_in signals.

from django.contrib.auth.signals import user_logged_in

class UserProfile(models.Model):
    ...
    login_count = models.PositiveIntegerField(default=0)

def login_user(sender, request, user, **kwargs):
    user.userprofile.login_count = user.userprofile.login_count + 1
    user.userprofile.save()

user_logged_in.connect(login_user)

Note that, it only counts actual login actions, where the previous session of the user is expired at the time he visits your site. If session is valid, he will not have to log in again so login_count won't be incremented.

So if you want to log user in whenever he opens his browser, you can tell session framework to set a browser-length cookie in your settings.py file:

SESSION_EXPIRE_AT_BROWSER_CLOSE = True    

Upvotes: 3

Related Questions