Populate and Validate a Django ModelForm using API Data with the Generic CreateView

I ran into a slightly tricky use case the other day wherein I needed to grab some data from an API, validate it against a Django ModelForm, and only show the form to the user if there are errors during the validation.

If the form is shown, the error messages from the validation should appear along with a pre-populated form (using the data from the API). Otherwise, the ModelForm should submit and be saved immediately, without any user interaction.

After digging through Django’s code it became clear that to accomplish this, I needed to override a couple methods of the generic class-based CreateView.

Here’s the code for the view…

As you can see, the first thing I’m doing is overriding get_form_kwargs so that it can take a new argument – data. This allows me to pass in the data pulled from the API to the form. Since I want the form to be saved immediately, without any user interaction, I set both the initial and data properties to the passed in data.

The get method is now a simple exercise in pinging the API for data, placing it into a dictionary the form can use, and calling form.is_valid() to see if the data passes the validation.

If it doesn’t, the form is rendered (complete with validation errors and pre-populated data) and the post method handles when the form is submitted by the user.

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’] = self.object.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 urls.py):

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 ModelForm and Conditionally Disabled (Readonly) Fields

I ran into a use case today that required a model form to have some fields disabled (readonly), but only when a certain condition was met (specifically when a property of the model was set to true) . Since the model form is used with the fields both enabled and disabled, simply duplicating the model form and removing the necessary fields wasn’t an option (plus that’s not exactly DRY now is it).

The solution ended up being quite simple. First, you’ll need to override the clean method for each field that needs to be disabled within your model form class:

The clean field method simply checks the is_disabled property and if it’s true, returns the existing field data. It only returns the new submitted data, pulled from cleaned_data, if is_disabled is false.

The second part of the solution is to set the field to readonly in your template. Note that you need to use readonly rather than disabled as the field won’t actually be submitted if set to disabled (more info on this here). This will cause Django to throw a missing field error before the clean field method ever runs.

You can add the necessary html to the form field via the widget’s attributes property:

Django ModelForms and request.user

Took a little bit of digging to figure this one out. If you’re using a ModelForm along with django.contrib.auth.models.User (or a customized User model), you’ll want to use the instance that is sitting in the request rather than allowing the ModelForm to create a new instance.

To do this, simply override the get_form_kwargs method in the view:

Subclass a Django Model Form and Add Extra Fields

A common use case of forms is to subclass some type of base form and add a couple extra fields. Take the following base form for example:

The model has a variety of other fields in it so I’m using fields in the Meta class to limit to just these three. Now let’s add a couple fields in a subclass:

As you can see, rather than re-specifying all the fields in the Meta class I am simply adding the new fields to the parent’s existing field list.

Using Your Django Model’s max_length in Your ModelForm

Let’s say you have a field defined as the following in your model:

You can then use the max_length in your ModelForm like this: