Yuval Adam

Django @login_required Decorator With 403

Django has a neat decorator called @login_required which - when attached to a view - ensures that request.user is logged in, and otherwise redirects the user to the login page (as defined in LOGIN_URL).

However, in AJAX calls this has no meaning. In most applications, AJAX calls should fail, preferably with a 403 (unauthorized) HTTP return code. Interestingly enough, Django has no such decorator.

So I just took the regular Django @login_required and modified it to immediately fail with 403 if the user is not authenticated. Enjoy -