[Django]-Django auto logout and page redirection

0👍

  1. After 40 seconds, logout happens but it is not visible in frontend, login page comes only if the user refreshes the tab or makes any request in the tab.

Yes, that is how it works. Your browser won’t do anything automatically. You’ll have to write necessary Javascript code to monitor the age of the session cookie. And when it expires, your Javascript code will load the login page.

  1. If I close the browser and open it again , the home page appears with no data as the data are user specific . and if refresh is done of tab is done , the tab is redirected to login page.

That doesn’t sound right. If you re-open your browser and visit your app’s homepage, it should take you to login page. But are you trying to restore your browser’s session after re-opening it (Ctrl + Shift + T)?

👤xyres

0👍

Auto logout.

Add the below two values in settings.py file:

1.SESSION_COOKIE_AGE = TIME #//change expired session

Example: SESSION_COOKIE_AGE = 240*60   #//four hours  or your time
  1. SESSION_SAVE_EVERY_REQUEST = True

############################################################

And then add the below jquery code in your base.html file:

    function autorefresh() {

            // auto refresh page after 1 second

            setInterval('refreshPage()', 6*1000);

    }


    function refreshPage() {

            $.ajax({

            url: window.location.pathname,

            success: function(data) {

                window.location = "."

            // $('#console').html(data);

            }

        });

    }

</script>

<script>autorefresh()</script>

<div id="console" ></div>

0👍

add a session.js file in your static/js folder and in your base.html file:

var time = new Date().getTime();

$(document).on("mousemove keypress scroll touchstart", function(e) {
    time = new Date().getTime();
});

function refresh() {
    if(new Date().getTime() - time >= 300000) //300000 = 5 minutes
        window.location.reload(true);
    else 
        setTimeout(refresh, 10000);
}

setTimeout(refresh, 10000);

if (window.history.replaceState) { 
    window.history.replaceState(null, null, window.location.href);
}

Leave a comment