Django - how do i force a user to change password on their first login using the last_login field of django.contrib.auth

Im using the django.contrib.auth. The code below is the working login function in my views.py

    #function based
def user_login(request):

    if request.method == "POST":
        username = request.POST['login-username']
        password = request.POST['login-password']
        user = authenticate(request, username = username, password = password)

        if user is not None:
            login(request, user)


            return redirect('dashboard')
            
        else:
            
            return render(request, 'authenticate/login.html', {})

    else:

        return render(request, 'authenticate/login.html', {})

Below is my attempt to check whether if the last_login is NULL. If so, redirect the user to the change-password page. It logs the newly created user (with NULL in the last_login field) but it does not redirect to the change-password page. I have tried changing the placement of the if statement. How do i correctly do this?

def user_login(request):

    if request.method == "POST":
        username = request.POST['login-username']
        password = request.POST['login-password']
        user = authenticate(request, username = username, password = password)

        if user is not None:
            
            if user.last_login == NULL:
                login(request, user)

                return redirect('change-password')

            else:
                login(request, user)
                return redirect('dashboard')
            
        else:
            
            return render(request, 'authenticate/login.html', {})

    else:

        return render(request, 'authenticate/login.html', {})

if you want to use last_login you should create new field also created_at for example and compare this two field with redirect user

or

I suggest to add new field (boolean field) and but the default value for it is false, when any user login check if it False or True, in the first login redirect user to change password and update this field to True

good luck

I figured the solution to my own question:

def user_login(request):

    if request.method == "POST":
        username = request.POST['login-username']
        password = request.POST['login-password']
        user = authenticate(request, username = username, password = password)

        if user is not None and user.last_login is None:
            login(request, user)
            return redirect('change-password')
            
        elif user is not None and user.last_login is not None:
            login(request, user)
            return redirect('dashboard')

        else:
            messages.error(request, ("Login error!"))
            return render(request, 'authenticate/login.html', {})
            

    else:

        return render(request, 'authenticate/login.html', {})
Back to Top