How to deploy machine learning model using Django?

Django is a high-level Python framework for creating scalable and robust web applications. In Python, this is the most widely used framework. It adheres to the MVT (Model-View-Template) design pattern. Other MVC frameworks, such as Ruby on Rails and Laravel, are closely linked to it. The display and model elements of the MVC framework are managed by the Controller, but in Django, the framework handles the tasks of a controller implicitly. Django allows you to develop several applications within a single project. The application has all the necessary features to function independently. The app is regarded as a package that may be reused in other applications without major modifications. This is the most significant benefit of using Django to create web apps.

What is Django REST Framework?

The Django REST framework is an excellent tool for building strong web APIs with Django and Python. It allows you to easily serialize data and share it with other programs. It acts as a barrier between the database and the application that performs database queries and data formatting. In most cases, JSON is used to format the data.

Ways to Integrate Machine Learning models in Django

Models for machine learning are typically developed in Python and executed locally in a Jupyter notebook or other IDEs (Integrated Development Environment). To make your machine learning model available on a web application, the following can be done.

In web apps, hard code the ML model. This is the simplest approach to deploy machine learning models on the web, such as support vector machine or linear regression classifiers. However, if you're trying to create more complex models like Neural Networks, it has a lot of limitations.

The most efficient method is to create a communication interface between the ML model and the web interface. It will acquire data for the model, which will then process it on its own. This interface will navigate you back to the web application's end once you've received the prediction from the model. We can do this through REST APIs or WebSocket.

Integrating a Diabetes Prediction Model in a Django Project

There are a few steps to integrate your machine learning model in a Django project.

  • Firstly, you will need to download the machine learning model as a .py file.

  • Then, the model should be saved after training to avoid overfitting.

  • Later, an app should be created that takes user data through an HTML form and output the prediction.

Let us begin integrating the model with a Django project.

In the example, example is a Django project and mlmodel is a Django App in example project.

Next step is to create a Django app which will contain the links to this model.

We have to create a .py file of the machine learning model. You can download the notebook as a python file in Jupyter and Google Colab.

Then, since training the model multiple times on the same data can cause overfitting, we will save the model in a file. This can be done by using the joblib library, that lets you dump the model in a .sav file. This step cannot be skipped because the accuracy of the model will be affected if the model once trained is not saved.

#Training the model
#fitting triaining data to the classifier,y_train)
filename= 'saved_model.sav'

The above piece of code shows how a model can be saved using the joblib library.

Then, we will work on templates, the HTML code through which user will enter data and the prediction will be shown. So, we will require form.html and result.html pages.

The form.html will contain a HTML form which will take all the necessary fields as input and upon submitting the form, the user will be redirected to result.html, where the prediction will be displayed.

Then, we have to save the saved model, the .py file and the dataset in the same folder as the app.

After this, the file structure of the project will be as follows.

Then, you can write and for the mlmodel app and run the application.

The should contain information that lets the computer know, which link to redirect to which page.

In this example, I have taken a diabetes prediction model and integrated it with a Django project. in mlmodel
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [

The will contain code on how to process the user entered information.

from django.shortcuts import render
from django.http import HttpResponse
import joblib
import numpy as np
def diabetes(request):
   return render(request, 'diabetes.html')
def result(request):
   lis.append(request.GET['Blood Pressure'])
   lis.append(request.GET['Skin Thickness'])
   data_array = np.asarray(lis)
   arr= data_array.reshape(1,-1)
   ans = cls.predict(arr)
      finalans='You may have diabetes'
      finalans = 'You do not have diabetes'
   return render(request, "result.html",{'ans':finalans})

The templates can be made as per the developer’s choice. But the result page should print the ‘ans’ sent by the file.

The form the user will have to enter data in, can look something like the below screenshot.

The result page can look something like the below screenshot.

You have successfully integrated a machine learning model in a Django project.

Updated on: 05-Sep-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started