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…


One thought on “Django Mixins – RequireSignInAjax and JSONResponseMixin”

  1. Hi Chris,

    A little unrelated comment however I thought I should point it out. There is also a LoginRequiredMixin (plus PermissionsRequiredMixin) available which might be of good use to people looking for alternatives to decorators and want to limit Views to only authenticated users.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s