Home > Mobile >  Django admin users timein and timeout of the user
Django admin users timein and timeout of the user

Time:06-19

Hi I am new in Django framework, I just want to know if is it possible to capture the timein and timeout of the user, I have this model that if the employee1 login on django-admin it will add automatic record and if the user click logout it will update the time-out. What I want is for every time the employee login in django admin it will add record and it will update the record once the employee logout, just like daily attendance record on company.

class UserLogs(models.Model):
    user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
    time_in = models.DateTimeField(default=now)
    time_out = models.DateTimeField(null=True, blank=True)

CodePudding user response:

you can use the Login and logout signals: user_logged_in, user_logged_out and user_login_failed signals to do this. Documentation

Here is an example usage (add these to your models):

@receiver(user_logged_in)
def post_login(sender, request, user, **kwargs):
    print(f'User: {user.username} logged in')
    user.time_in = datetime.now()
    user.save()

This acts as a "Watcher" function that triggers when the user logs in. Similar for logging out.

  • Related