Machine Learning: Diabetes Prediction Project in Django

In recent years, machine learning has brought about a revolution in various industries, and the healthcare field is certainly no exception. By harnessing the immense power of data and algorithms, machine learning empowers us to develop predictive models that play a vital role in disease detection and management. In this article, we will involve ourselves in the world of machine learning as we explore the creation of a remarkable diabetes prediction project using Django is high−level Python web framework. By exploiting the inherent flexibility of Django and integrating machine learning algorithms, we can construct an exceptionally robust application capable of predicting the likelihood of diabetes based on user inputs. This project serves as a testament to the vast potential of machine learning in the realm of healthcare, offering a truly invaluable tool for early intervention and personalized healthcare. Join us on this captivating journey as we combine cutting−edge technology and web development to address one of the most prevalent diseases affecting people worldwide.

Step 1: Setting up the Django Project

To begin with, let's set up our Django project for the diabetes prediction application. Now Launch your terminal or command prompt and enter the following commands:

$ django-admin startproject diabetes_prediction
$ cd diabetes_prediction

This command will create a new Django project called "diabetes_prediction" and automatically navigate me to the project directory.

Step 2: Creating the Diabetes Prediction App

In Django, an app is a self−contained module that represents a specific functionality within a project. To create our diabetes prediction app, run the following command in the terminal:

$ python startapp prediction

This command will generate a new app called "prediction". Now, we need to configure the app within my project. We will open the diabetes_prediction/ file and add 'prediction' to the INSTALLED_APPS list.

Step 3: Building the Machine Learning Model

In our diabetes prediction project lies the machine learning model. To train a classifier on a diabetes dataset and make accurate predictions, we will leverage the scikit−learn library. To implement this, we create a new file called prediction/ and include the following code:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

class DiabetesPredictor:
    def __init__(self):
        self.model = None
        self.features = ['feature1', 'feature2', 'feature3', ...]  # Replace with actual feature names

    def train(self):
        data = pd.read_csv('diabetes.csv')  # Replace with your dataset file

        X = data[self.features]
        y = data['target']

        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

        self.model = RandomForestClassifier(), y_train)

    def predict(self, input_data):
        input_df = pd.DataFrame([input_data], columns=self.features)
        prediction = self.model.predict(input_df)
        return prediction[0]

Make sure to replace 'feature1', 'feature2', 'feature3', ... with the actual feature names from your dataset.

Step 4: Creating the Django Views and Templates

Views in Django manage user requests and deliver responses. Let's build an idea to manage the form submission and show the forecast outcome. Add the following code to the prediction/ file by opening it:

from django.shortcuts import render
from .ml_model import DiabetesPredictor

def predict_diabetes(request):
    if request.method == 'POST':
        predictor = DiabetesPredictor()

        input_data = {
            'feature1': request.POST['feature1'],
            'feature2': request.POST['feature2'],
            'feature3': request.POST['feature3'],
        }  # Replace with actual feature names

        prediction = predictor.predict(input_data)

        return render(request, 'prediction/result.html', {'prediction': prediction})

    return render(request, 'prediction/form.html')

Step 5: Setting up the URL Routing

URL routing in Django maps URLs to views, allowing users to access different pages and functionalities within a web application. Let's configure the URL routing for our diabetes prediction project.

Here’s an example code:

from django.urls import path
from . import views

app_name = 'prediction'

urlpatterns = [
    path('', views.predict_diabetes, name='predict_diabetes'),

This code snippet configures URL routing in Django by importing required functions and modules, defining a URL pattern for the root URL, associating it with a specific view function, and assigning a unique name for reference. The view function handles requests and generates responses when users access the root URL.

Step 6: Creating the HTML Templates

Next, we will create the HTML templates for our web application. We establish a new directory called "templates" after navigating to the prediction directory. We add two new files, form.html, and result.html, to the templates directory.

In form.html, add the following code:

<!DOCTYPE html>
    <title>Diabetes Prediction</title>
    <h1>Diabetes Prediction</h1>

    <form action="{% url 'prediction:predict_diabetes' %}" method="POST">
        {% csrf_token %}
        <label for="feature1">Feature 1:</label>
        <input type="text" name="feature1">

        <label for="feature2">Feature 2:</label>
        <input type="text" name="feature2">

        <label for="feature3">Feature 3:</label>
        <input type="text" name="feature3">

        <!-- Add more input fields for other features -->

        <button type="submit">Predict</button>

In result.html, add the following code:

<!DOCTYPE html>
    <title>Diabetes Prediction Result</title>
    <h1>Diabetes Prediction Result</h1>

    <p>Prediction: {{ prediction }}</p>

Step 7: Running the Application

Finally, it's time to run our diabetes prediction application.

Here’s an example code to run the application:

$ python runserver

Go to the following URL in our web browser: http://localhost:8000/prediction/. When we arrive at the webpage, an interactive form will be displayed, allowing us to enter the required information. When we fill out the form and submit it, the program processes the data and displays the prediction outcome right away.


In conclusion, we have demonstrated the process of developing a diabetes prediction project using machine learning in Django. By leveraging the power of scikit−learn and Django, we were able to create an interactive web application that can predict the likelihood of a person having diabetes based on input features. Through the steps of setting up the Django project, building the machine learning model, creating views and templates, and running the application, we have shown how to bring together the worlds of machine learning and web development. With this knowledge, you can now embark on your own projects, utilizing Django's versatility and machine learning's predictive capabilities.

Updated on: 25-Jul-2023


Kickstart Your Career

Get certified by completing the course

Get Started