问题
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 there a message api for expired sessions in Django?
I poked around and didn't see anything for setting an expired session message.
Thanks!
回答1:
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.
回答2:
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'))
回答3:
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)
来源:https://stackoverflow.com/questions/5200787/django-expired-session-message-api