Debugging Django & Ajax

UPDATE: See Peter’s comment below for a slightly revised (and better) version of this.

The Django Debug Toolbar is essential for developing Django applications but it comes short in one area – Ajax. There’s been progress over the last couple years but the latest pull request for a panel that supports Ajax has yet to be completed and merged. This leaves you pretty much in the dark when making XHR requests as the toolbar only works if the mimetype of the response is either text/html or application/xhtml+xml and contains a closing </body> tag (otherwise your XHR requests would be filled with a bunch of junk from the toolbar).

After digging around I stumbled upon this SO post which details a few solutions including using the following middleware:

Add this middleware right after the debug toolbar in your settings (and ensure that it is only enabled for your dev environment) and then load an Ajax URL directly in a browser tab. The middleware simply detects that you’re not making this request as Ajax and wraps the response in some HTML which will activate the debug toolbar. Very handy.

It’s definitely a bit of a hack and doesn’t make working with posts very easy, but it’s better than nothing.

Advanced Django Class-based Views, ModelForms and Ajax Example Tutorial

Reading the Django docs for working with class-based views, modelforms, and ajax left me with more than a few questions on how to properly architect them. After much trial and error I’ve landed on what I think is a good, re-usable structure.

The following will walk through a fairly complex example that uses modelforms, an ajax response mixin, some ajax helper methods, and exception middleware.

Let’s start off with a basic model:

As you can see we have just a single field, name. Now let’s create the modelform:

The reason I’m created my own modelform rather than allowing Django to auto-generate one for me is that I’d like to set the max_length parameter on the field and control which fields are updated when the model is saved. This comes in very handy when working with larger models where you only want to write a subset of fields to the database.

It’s worth noting here that even though I’ve specified only the name field in the Meta class’s fields, Django will still update all fields when saving the model unless you explicitly declare the fields to update using update_fields.

Next is the view:

The view is doing a couple of very important things:

  • A mixin is being used to add ajax functionality to the view (more on this below)
  • The form_class is set to our model form
  • The object is fetched using a custom helper function called get_object_or_json404 (more on this below)
  • And a success parameter is set on the context (for when a form is successfully saved)  (you could add any additional values you would like including values from object instance using self.object – i.e. context[‘name’] =

You could also require authentication for this view by using this mixin.

Let’s look at the mixin:

This is a simple mixin that overrides the default form_invalid and form_valid functions to return json instead of their usual HttpResponse and HttpResponseRedirect, respectively. A couple of key things are happening in this mixin:

  • Another helper function called render_to_json_response is used to generate the json (more on this below)
  • The form_invalid method returns a 400 status code along with the form errors (it does not include the context)
  • The form_valid method saves the form and returns the context as json using the get_context_data method that was created in the view above

Now let’s have a look at the helper methods:

The first method, get_object_or_json404, is a replacement for django.shortcuts.get_object_or_404() and allows json to be returned with a 404 error. It makes use of a custom exception, JsonNotFound, which we’ll look at shortly.

The second helper method, render_to_json_response, converts the context to json (using a third helper method, convert_context_to_json), sets the content type to application/json, and returns everything using HttpResponse.

The custom exception allows us to trap record not found errors and return an error message as json as well. Here’s the exception:

And here’s the middleware necessary to include the custom exception in your application (you don’t have to get this fancy with an error code and timestamp, but the 404 status and descriptive error message are a must):

Ensure the middleware is added to your application settings:

Finally, let’s create a new route for our class-based view (in

You can now post to your view and receive a json response with a corresponding status code (400, 404, or 200 – and 401 if you use the authentication mixin). Here’s some sample javascript to get you going:

Lots to digest but hopefully this is straightforward and easy to implement. If you have any suggestions for improvements, please let me know in the comments.

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…