django-ajax-redirect

AJAX redirection middleware and decorator for Django


License
MIT
Install
pip install django-ajax-redirect==0.1.0

Documentation

django-ajax-redirect

Transforms HTTP responses status code on-the-fly to allow AJAX clients to handle redirects.

Usage

Django

As a middleware

It should appear after any middleware that could produce an HttpResponseRedirect.

MIDDLEWARE_CLASSES = [
    # [...]
    'ajax_redirect.middlewares.AjaxRedirectMiddleware',
]

Be aware that if included as a middleware, it will act on every AJAX requests.

As a FBV decorator

@ajax_redirect
def my_view(request):
    # [...]
    return redirect('/redirect/url/')

As a CBV decorator

# At class-level...
@method_decorator(ajax_redirect, 'post')
class ThingCreateView(CreateView):

    # OR at method-level
    @method_decorator(ajax_redirect)
    def post(self, request):
        # [...]
        return HttpResponseRedirect('/redirect/url/')

Client-side

As an Angular.js interceptor

.config(function ($httpProvider) {
    $httpProvider.interceptors.push('AjaxRedirectInterceptor');
})

.factory('AjaxRedirectInterceptor', function ($window) {
    return {
        response: function (response) {
            if (response.status == 278) {
                $window.location.href = response.headers('Location');
            }
            return response;
        }
    };
});

As a jQuery callback (not tested)

$(document).ready(function() {
    $('body').ajaxComplete(function(e, xhr, settings) {
        if (xhr.status == 278) {
            window.location.href = xhr.getResponseHeader('Location');
        }
    });
});