Home > Enterprise >  Django - stop logout with javascript pop-up confirm box
Django - stop logout with javascript pop-up confirm box

Time:01-09

In my django site I have a logout button that redirects to the view logout. When the button is clicked it instantly logs the user out, but I would like a JS pop-up confirm box to appear then the logout button is clicked.

When the user clicks 'Ok' OR 'Cancel' it logs the user out. How can i prevent the logout view being called when the user clicks 'Cancel'?

views.py

def logout(request):
    if "user_info" in request.session:
        del request.session["user_info"]
    #redirect to login so the user can log back in
    return redirect("login")

script.js

function logout_popup() {
    if (confirm("Are you sure?")) {
        window.location.reload()
    }
}

base.html

<li onclick="logout_popup()" id="logout-tab"><a href="{% url 'logout' %}">Logout</a></li>

CodePudding user response:

Try to move the onclick to the a tag:

<li id="logout-tab"><a onclick="logout_popup(event)" href="{% url 'logout' %}">Logout</a></li>

and the script:

function logout_popup(e) {
    if (confirm("Are you sure?")) {
        window.location.reload()
    } else {
        e.preventDefault()
    }
}
  • Related