Last active
May 2, 2022 16:32
-
-
Save mesuutt/86d12670ba52165c8621410690386010 to your computer and use it in GitHub Desktop.
Django handling expired session (for ajax request)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.ajaxSetup({ | |
complete: function(xhr, status) { | |
if(xhr.status == 278) { | |
if (xhr.responseJSON) { | |
var data = xhr.responseJSON; | |
if (!data.success && data.error_message) { | |
alert(data.error_message); | |
} | |
} | |
setTimeout(function() { | |
window.location = xhr.responseJSON.redirect_to; | |
}, 2000); | |
} | |
} | |
}); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import messages | |
from django.http import HttpResponseRedirect, JsonResponse | |
from django.urls.base import reverse | |
from django.utils.translation import gettext as _ | |
from django.utils.deprecation import MiddlewareMixin | |
class AjaxRedirectHandlerMiddleware(MiddlewareMixin): | |
""" | |
Middleware for AJAX redirects in Django. | |
""" | |
def process_response(self, request, response): | |
# If session expired, Django will send HttpResponseRedirect to login page. | |
if request.is_ajax() and type(response) == HttpResponseRedirect: | |
if not request.user.is_authenticated: | |
# Show an additional message on login page after redirect. | |
messages.error(request, _('Session expired. Please login again.')) | |
response = JsonResponse(data={ | |
'success': False, | |
'error_message' _('Session expired')}, | |
'redirect_to': reverse('account:login'), | |
}) | |
response.status_code = 278 | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment