Introduction to Deploying Machine Learning Models with Django

In this article we introduce key concepts of the Python-based framework called Django for deploying machine learning models.

4 years ago   •   5 min read

By Peter Foy

One of the rarest and most desirable skills in tech is the ability to combine machine learning and data science skills with practical web development.

In this article we're going to introduce key concepts of the Python-based framework called Django for deploying machine learning models to a web app.

The article is based on this course on full stack web development and machine learning and covers the following topics:

  • What is Django?
  • Setting Up a Django Project
  • What is MVC?
  • Creating URLs & Views with Django
  • Django Template & Settings
  • Input & Output with Django
  • Using Python Scripts with Django
  • Integrating a Machine Learning Model into Django

What is Django?

Django refers to itself as:

The web framework for perfectionist with deadlines

This means the framework encourages quick development of clean web apps.

A few recognizable websites that use Django include Instagram, Pinterest, YouTube, and Spotify, and many others.

Since Django is written in Python it makes it a great choice of web framework for deploying machine learning models.

Setting Up a Django Project

To set up a Django project we first we need to pip install django and then let's create a folder for the project with mkdir django-project.

Next we want to create a project with django-admin startproject first_project.

Now if we run python3 runserver and go to our local host we can see that Django has been successfully installed and is running.

Stay up to date with AI

We're an independent group of machine learning engineers, quantitative analysts, and quantum computing enthusiasts. Subscribe to our newsletter and never miss our articles, latest news, etc.

Great! Check your inbox and click the link.
Sorry, something went wrong. Please try again.

What is MVC?

The Model-View-Controller software design pattern is commonly used in Django as it's an effective way of structuring a dynamic website (i.e. it uses stored data).

Let's briefly review key MVC concepts:

  • Model - this handles the dynamic data structure (i.e. the databse)
  • View - this is what the user can see and interact with
  • Controller - the controller is the middle man that accepts inputs and converts it to commands for the model or view

Creating URLs & Views with Django

Now let's create our first web page with Django.

Let's create a new folder called views_urls, create a new Django project, and run the server again.

Next we'll create our own web page called in our project and add it to

Now in we will create a function for our home page with the following:

from django.http import HttpResponse

def home(request):
    return HttpResponse("This page is working!")

Next we need to add our home page to as follows:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home )

Django Template & Settings

Now that we've created a basic web page let's expand on this and look at how we can return more complete HTML pages with Django's templates and settings.

Templates is a folder that we create and in that folder we put in all of our HTML pages.

Next we want to let Django know that we have this folder, so in we can add 'templates' to our 'DIRS' as follows:

Now we can start creating HTML files in our templates folder.

Now let's go into we're going to change what we're importing from Django from HttpResponse as follows:

from django.shortcuts import render

def home(request):
    return render(request, 'index.html')

Input & Output with Django

Now that we have a single working webpage with Django, the next step to build a machine learning app is to allow a user to input some information - for example, if we're using the classic Titanic survivors machine learning problem we want users to be able to input variables like age, spouses, children, etc.

Next we want to run the model and display the prediction if they survived or not.

First we'll add a new page to called result and create a result.html file that will retun the prediction, and we'll also add a link to go back to the home page.

Next we'll add a form txo our index.html that will take in information and go to the results page.

To actually display an output we'll add user_input = requestt.GET["age"] to our result function in

For now in our result.html we'll put in a placeholder with whatever the user put in the age variable.

Now that we've got the input and output of our Django app setup, it's time to add a machine learning script.

Using Python Scripts with Django

Before we import the entire code from our Titanic machine learning model, let's briefly review how to run Python scripts in Django.

First we want to create a new Python file with a simple placeholder function, for example if their age is over 10 we'll say they survived.

Next we import the function into and create a new variable for our prediction as follows:

def result(request):
    user_input_age = int(request.GET["age"])
    prediction = fake_model.fake_predict(user_input_age)
    return render(request, 'result.html', {'prediction':prediction})

Next we have to change what we're displaying in result.html to prediction and we have a working Python script in Django.

Integrating a Machine Learning Model into Django

Now that we have a multipage site that can take input from the user, run it through a Python script, and output the result we're ready to integrate a machine learning model.

While the code for the Titanic model is beyond the scope of this article, all we need to do is save the trained model to our local computer and upload that into our Django app so that we can make predictions with it.

Next we will use the following Python script and add it to our project to perform inference on our trained model:

def prediction_model(pclass,sex,age,sibsp,parch,fare,embarked,title):
    import pickle
    x = [[pclass,sex,age,sibsp,parch,fare,embarked,title]]
    randomforest = pickle.load(open('titanic_model.sav','rb'))
    prediction = randomforest.predict(x)
    return prediction

Now we want to import this into, add variables for each of the input variables, and also add these variables to our index.html page.

As we can see, as we input each of the variables we get the following prediction:

Summary: Deploying Machine Learning Models with Django

Of course this Django app desperately needs some CSS, but for the purpose of this article it serves as a starting point for deploy a machine learning model with Django.

In summary, we've set up a multipage website that takes input from users, perform inference on a pre-trained machine learning model, and returns the prediction as output.


Spread the word

Keep reading