[Django]-Django post time to database

4👍

You can use auth.model.User.last_login to get the last login time of the user, assuming you are using Django’s built-in authentication:

user = User.objects.get(username='johndoe')
last_login = user.last_login

If you want to store this data somewhere else other than User table, you can simply insert this last_login to the table you want. Otherwise, it is already in models.User.

As for recording logging out, you can use the following view for your logout view:

from django.contrib.auth import logout
from django.utils import timezone

def logout_view(request):
    logout(request)
    logout_time = timezone.now()
    # Now save your logout_time to the table you want
    # Redirect to a success page.

Alternatively, you can utilize Django’s user_logged_out signal (available in Django 1.3+) to record the last logout time each time a user logs out:

from django.contrib.auth.signals import user_logged_out

def update_last_logout(sender, user, **kwargs):
    """
    A signal receiver which updates the last_logout date for
    the user logging out.
    """
    user.last_logout = timezone.now()
    user.save(update_fields=['last_logout'])
user_logged_out.connect(update_last_logout)

You can put this at the bottom of your models.py file. Note that the solution above assumes you would extend User model to include last_logout field. If you aren’t sure how you would go about doing that, you can start from here: Django Tip 5: Extending contrib.auth.models.User.

In fact, the second approach is exactly how Django updates last_login for User: models.py.


Reference:

  1. Official Django doc on last_login
  2. Extending contrib.auth.models.User
👤K Z

Leave a comment