开发者

Django Expired Session Message API

I'm currently using SESSION_COOKIE_AGE = 60*60 to expire a Django session in 1 hour. I need to give a message to the user saying their session has expired on the login page.

Is there a way to test if the session has been expired? Or is开发者_StackOverflow there a message api for expired sessions in Django?

I poked around and didn't see anything for setting an expired session message.

Thanks!


To display the message that session is expired you can check if session exists in your logout view and change the success message accordingly

class Logout(View):
def get(self, request):
    if request.session:
        messages.success(request, 'Successfully Logged Out')
    else:
        messages.error(request, 'Session Expired Please Login Again')
    logout(request)
    return redirect(reverse('login'))


The warning typically provided to a user is an invitation to login :-).

What you could do is check SESSION_COOKIE_AGE (which provides the age of the cookie in seconds) and, if the user's session is about to expire, provide a warning to that effect.


I encouraged same problem and solved shown as below:

Django redirecting to LOGIN_URL after session expired. So I pointed login url to logout view in settings.py for show message to user and redirect to our login view.

settings.py:

LOGIN_URL = reverse_lazy('account:logout') 

views.py:

class LogoutView(RedirectView):
    url = reverse_lazy('account:login') # Our login view

    def get(self, request, **kwargs):

        # If session expired django clean request.session object.
        # If user came to this view by clicking to logout button request.session not comes empty 
        if request.session.is_empty():
            messages.error(request, "Your session has expired. Please login again to continue checking out.")

        logout(request)

        if request.GET.get('next'):
            self.url = '{}?next={}'.format(self.url, request.GET.get('next'))

        return super(LogoutView, self).get(request, **kwargs)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜