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.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s