Search code examples
djangopython-2.7authenticationdjango-authentication

Can I check if a user is logged in for the first time after this user is logged in? - Django


I'm trying to catch the first time someone logs in so I can redirect him/her to another page then normally.

I'm working with groups. A admin can make a group with multiple users (with generated usernames and passwords). So it can be that a user is already created before the user logs in (There is no register form for just one user)

This is the code that I want:

def index(request):
    if request.user:
        user = request.user
        if user.last_login is None:
            return redirect('profile')
        else:
            return redirect('home')
    else:
        return redirect('/login')

I've read about checking user.last_login but for this case that doesn't work because it checks this method AFTER the user logs in. Which means that user.last_login is never None.

Can someone help me how can see when a user logs in for the first time?


Solution

  • The last_login value is set via a signal which happens at login, but before your code executes, so you never see None as you've discovered.

    One way to achieve what you want could be to register your own signal receiver to set a first_login attribute somewhere, e.g. in the user's session, before updating the last_login value.

    from django.contrib.auth.signals import user_logged_in
    from django.contrib.auth.models import update_last_login
    
    def update_first_login(sender, user, **kwargs):
        if user.last_login is None:
            # First time this user has logged in
            kwargs['request'].session['first_login'] = True
        # Update the last_login value as normal
        update_last_login(sender, user, **kwargs)
    
    user_logged_in.disconnect(update_last_login)
    user_logged_in.connect(update_first_login)
    

    Then in your view, you'd just need to check the session for the first_login attribute.

    def index(request):
        if request.user:
            if request.session.get('first_login'):
                return redirect('profile')
            else:
                return redirect('home')
        else:
            return redirect('/login')