Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django – stop logout with javascript pop-up confirm box

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading