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 explore creating a diabetes prediction project using Django, a high?level Python web framework. By exploiting the inherent flexibility of Django and integrating machine learning algorithms, we can construct a robust application capable of predicting the likelihood of diabetes based on user inputs.

Step 1: Setting up the Django Project

To begin with, let's set up our Django project for the diabetes prediction application. 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 navigate 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 ?

python manage.py startapp prediction

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

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'prediction',  # Add this line
]

Step 3: Building the Machine Learning Model

The core of our diabetes prediction project lies in the machine learning model. We'll use the Pima Indians Diabetes Dataset, which includes features like glucose levels, blood pressure, and BMI. Create a new file called prediction/ml_model.py ?

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
import pickle
import os

class DiabetesPredictor:
    def __init__(self):
        self.model = None
        self.scaler = None
        self.features = [
            'pregnancies', 'glucose', 'blood_pressure', 'skin_thickness', 
            'insulin', 'bmi', 'diabetes_pedigree', 'age'
        ]

    def create_sample_data(self):
        """Create sample dataset for demonstration"""
        np.random.seed(42)
        n_samples = 500
        
        data = {
            'pregnancies': np.random.randint(0, 10, n_samples),
            'glucose': np.random.randint(80, 200, n_samples),
            'blood_pressure': np.random.randint(50, 120, n_samples),
            'skin_thickness': np.random.randint(10, 50, n_samples),
            'insulin': np.random.randint(0, 300, n_samples),
            'bmi': np.random.uniform(15, 50, n_samples),
            'diabetes_pedigree': np.random.uniform(0, 2, n_samples),
            'age': np.random.randint(18, 80, n_samples)
        }
        
        df = pd.DataFrame(data)
        # Create target based on simplified rules
        df['target'] = ((df['glucose'] > 140) | 
                       (df['bmi'] > 30) | 
                       (df['age'] > 45)).astype(int)
        
        return df

    def train(self):
        # Create sample data (in real project, load from diabetes.csv)
        data = self.create_sample_data()
        
        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
        )

        # Scale the features
        self.scaler = StandardScaler()
        X_train_scaled = self.scaler.fit_transform(X_train)
        
        # Train the model
        self.model = RandomForestClassifier(n_estimators=100, random_state=42)
        self.model.fit(X_train_scaled, y_train)
        
        # Test accuracy
        X_test_scaled = self.scaler.transform(X_test)
        accuracy = self.model.score(X_test_scaled, y_test)
        print(f"Model accuracy: {accuracy:.2f}")

    def predict(self, input_data):
        if self.model is None or self.scaler is None:
            self.train()
        
        # Convert input to DataFrame and scale
        input_df = pd.DataFrame([input_data], columns=self.features)
        input_scaled = self.scaler.transform(input_df)
        
        # Make prediction
        prediction = self.model.predict(input_scaled)
        probability = self.model.predict_proba(input_scaled)[0][1]
        
        return {
            'prediction': int(prediction[0]),
            'probability': float(probability),
            'risk_level': 'High' if probability > 0.7 else 'Medium' if probability > 0.3 else 'Low'
        }

Step 4: Creating Django Forms

Let's create a Django form to handle user input validation. Create prediction/forms.py ?

from django import forms

class DiabetesPredictionForm(forms.Form):
    pregnancies = forms.IntegerField(
        min_value=0, max_value=20, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0-20'})
    )
    glucose = forms.IntegerField(
        min_value=0, max_value=300, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '70-200'})
    )
    blood_pressure = forms.IntegerField(
        min_value=0, max_value=200, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '60-120'})
    )
    skin_thickness = forms.IntegerField(
        min_value=0, max_value=100, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '10-50'})
    )
    insulin = forms.IntegerField(
        min_value=0, max_value=1000, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0-300'})
    )
    bmi = forms.FloatField(
        min_value=0, max_value=100, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '15-50'})
    )
    diabetes_pedigree = forms.FloatField(
        min_value=0, max_value=5, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01', 'placeholder': '0.0-2.0'})
    )
    age = forms.IntegerField(
        min_value=1, max_value=120, 
        widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '18-80'})
    )

Step 5: Creating Django Views

Views in Django handle user requests and deliver responses. Update the prediction/views.py file ?

from django.shortcuts import render
from django.contrib import messages
from .ml_model import DiabetesPredictor
from .forms import DiabetesPredictionForm

def predict_diabetes(request):
    if request.method == 'POST':
        form = DiabetesPredictionForm(request.POST)
        
        if form.is_valid():
            try:
                predictor = DiabetesPredictor()
                
                input_data = {
                    'pregnancies': form.cleaned_data['pregnancies'],
                    'glucose': form.cleaned_data['glucose'],
                    'blood_pressure': form.cleaned_data['blood_pressure'],
                    'skin_thickness': form.cleaned_data['skin_thickness'],
                    'insulin': form.cleaned_data['insulin'],
                    'bmi': form.cleaned_data['bmi'],
                    'diabetes_pedigree': form.cleaned_data['diabetes_pedigree'],
                    'age': form.cleaned_data['age'],
                }

                result = predictor.predict(input_data)
                
                context = {
                    'result': result,
                    'input_data': input_data
                }
                
                return render(request, 'prediction/result.html', context)
                
            except Exception as e:
                messages.error(request, f'Prediction error: {str(e)}')
        else:
            messages.error(request, 'Please correct the errors below.')
    else:
        form = DiabetesPredictionForm()

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

Step 6: Setting up URL Routing

Create prediction/urls.py for URL routing ?

from django.urls import path
from . import views

app_name = 'prediction'

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

Update the main diabetes_prediction/urls.py file ?

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('prediction/', include('prediction.urls')),
    path('', include('prediction.urls')),  # Root URL redirects to prediction
]

Step 7: Creating HTML Templates

Create the templates directory structure: prediction/templates/prediction/. First, create form.html ?

<!DOCTYPE html>
<html>
<head>
    <title>Diabetes Prediction</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <h1 class="text-center mb-4">Diabetes Risk Prediction</h1>
                
                {% if messages %}
                    {% for message in messages %}
                        <div class="alert alert-danger">{{ message }}</div>
                    {% endfor %}
                {% endif %}

                <form method="POST">
                    {% csrf_token %}
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Pregnancies:</label>
                            {{ form.pregnancies }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Glucose Level:</label>
                            {{ form.glucose }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Blood Pressure:</label>
                            {{ form.blood_pressure }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Skin Thickness:</label>
                            {{ form.skin_thickness }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Insulin:</label>
                            {{ form.insulin }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>BMI:</label>
                            {{ form.bmi }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Diabetes Pedigree:</label>
                            {{ form.diabetes_pedigree }}
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Age:</label>
                            {{ form.age }}
                        </div>
                    </div>
                    
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary btn-lg">Predict Diabetes Risk</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Create result.html to display the prediction results ?

<!DOCTYPE html>
<html>
<head>
    <title>Diabetes Prediction Result</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <h1 class="text-center mb-4">Diabetes Prediction Result</h1>
                
                <div class="card">
                    <div class="card-body text-center">
                        <h3>Prediction: 
                            <span class="{% if result.prediction %}text-danger{% else %}text-success{% endif %}">
                                {% if result.prediction
Updated on: 2026-03-27T09:56:12+05:30

738 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements