Skip to content

Instantly share code, notes, and snippets.

@mesuutt
Last active May 2, 2022 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mesuutt/86d12670ba52165c8621410690386010 to your computer and use it in GitHub Desktop.
Save mesuutt/86d12670ba52165c8621410690386010 to your computer and use it in GitHub Desktop.
Django handling expired session (for ajax request)
$.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);
}
}
});
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