Last modified: December 25, 2020

How to Show Last Login Date to User in Django

The last Login is one of the most properties that warn the user if his account has cracked.
Django provides us a last_login User filed that saves the last login time and date for each user.

In this tutorial, we're going to write a simple example that returns the last login DateTime of the user, But first, I just wanted to let you know how to use last_login filed.

Understand how to use the last_login field

Let's enter to Django shell:


python3 manage.py shell 

importing Django User Model:


>>> from django.contrib.auth.models import User

print last_login of the user:


>>> user_last_login = User.objects.get(username='saidox').last_login

output:


datetime.datetime(2020, 12, 9, 0, 35, 56, 136099, tzinfo=<UTC>)

To make output readable, we need to use the strftime() method.


>>> user_last_login.strftime('%y-%m-%d %a %H:%M:%S')

output:


'20-12-09 Wed 00:35:56'
 

Print just the date:


>>> user_last_login.date().strftime('%y-%m-%d)



'20-12-09 Wed'

Example of showing last_login of a user

After understanding how to use the last_login filed, let's now write an example that returns the Username and Last Login to the user.


#views.py

from django.contrib.auth.models import User

def last_login(request):
    if request.user.is_authenticated:
        user = User.objects.get(username=request.user)
        last_login = user.last_login.strftime('%y-%m-%d %a %H:%M:%S')
        return HttpResponse(
            f"""
            <h2>User: {request.user}</h2>
            <br>
            <h2>Last Login: {last_login}</h2>
            """
            )

    else:
        return HttpResponse("<h1>Please log in</h1>")

    return HttpResponse("<h1>Page Not Found</h1>", status=404)    



request.user: username


#urls.py

path("last-login", last_login),  

before login:

before login

Now, let's log in and see what happens.

after login

after login:

after login