count number of logins by specific user django?

前端 未结 4 2270
一个人的身影
一个人的身影 2021-02-09 05:19

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

相关标签:
4条回答
  • 2021-02-09 06:00

    There's also a 'user_logged_in' signal that'll do the trick with out the need to check for last logins etc.

    class UserLogin(models.Model):
        """Represent users' logins, one per record"""
        user = models.ForeignKey(user) 
        timestamp = models.DateTimeField()
    
    from django.contrib.auth.signals import user_logged_in
    
    def update_user_login(sender, user, **kwargs):
        user.userlogin_set.create(timestamp=timezone.now())
        user.save()
    
    user_logged_in.connect(update_user_login)
    
    0 讨论(0)
  • 2021-02-09 06:06

    You can use django-timeStamps to store rcent login times. A simple light weight tool.

    0 讨论(0)
  • 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 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.DateTimeField()
    
    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)
    
    0 讨论(0)
  • 2021-02-09 06:17

    This is how I did (using django 1.7), similar to Guy Bowden answer:

    from django.contrib.auth.models import User
    from django.contrib.auth.signals import user_logged_in
    
    class LoginUpdate(models.Model):
        date_updated = models.DateTimeField(auto_now_add=True, null=True)
        action_type = models.CharField(max_length=5)
        action_user = models.ForeignKey(User, null=True, blank=True)
    
    def update_user_login(sender, **kwargs):
        user = kwargs.pop('user', None)
        LoginUpdate.objects.create(action_type="Login", action_user=user)
    
    user_logged_in.connect(update_user_login, sender=User)
    

    Later you can count number of logins, in your views.

    0 讨论(0)
提交回复
热议问题