Django Mixins – RequireSignInAjax and JSONResponseMixin

So you’ve developed a secure section of your site and now you need to create an AJAX view… but that view needs to be locked down as well.

The RequireSignIn mixin in the previous post returns an HttpResponseRedirect which won’t work in this situation.

First, let’s lock down the view to require the user to be logged in when making an AJAX request.

Here’s what the mixin looks like:


You’ll notice that I’m making use of a method decorator – login_required_ajax. This decorator simply checks to see if the user is authenticated and if so, allows the request to continue. Otherwise it returns some json containing an error and the proper 401 http status which you could then use to ask the user to login.

Here’s the function:


Ok, now we’ve made sure the user is logged in. Let’s add a simple mixin (pulled from the Django docs), to return some json:


Finally, you can use these in your view like so…


Django Class-based Views

Class-based views were introduced in Django 1.3 and are very useful. This article discusses how to make use of them along with creating a mixin for requiring the user to be authenticated for a specific view.

I’ve tweaked the example a little bit, redirecting to the login page rather than a 404 and separating the mixin into a separate file.