From Model to Web App 🌐

A practical, step-by-step tutorial on integrating a machine learning model with the Django web framework.

The Project Blueprint 🏗️

Our plan involves two major phases: first, preparing our model, and second, building the web interface to use it.

Step 0: Prerequisites & Setup 🛠️
What You'll Need

Before we start, make sure you have Python and Pip installed. We will need three main libraries: Django for the web framework, and Scikit-learn & Pandas for our model.

Open your terminal or command prompt and install them:

pip install django scikit-learn pandas joblib
Note: We're also installing `joblib`, a library perfect for saving and loading Python objects, which is exactly what we need for our trained model.
Step 1: Train & Save The Model (The "Offline" Phase) 🧠
Why We Save The Model

Training a model can take minutes, hours, or even days. We cannot retrain our model every time a user visits our website. Instead, we perform a one-time training process and then **save the trained model to a file**. Our web application will then simply **load** this pre-trained model to make instant predictions.

The Training Script

Create a Python file named `train_model.py`. This script will contain the code from our first tutorial, with one crucial addition at the end: saving the model.

# train_model.py

import pandas as pd
from sklearn.linear_model import LinearRegression
import joblib

# 1. Our historical data
data = {
    'Size (sqft)': [1500, 2000, 1200, 2800, 1800],
    'Price ($k)': [300, 410, 250, 550, 350]
}
df = pd.DataFrame(data)

# 2. Prepare the data for scikit-learn
X = df[['Size (sqft)']]
y = df['Price ($k)']

# 3. Create and train the model
model = LinearRegression()
model.fit(X, y)
print("Model trained successfully!")

# 4. Save the trained model to a file
joblib.dump(model, 'house_price_model.joblib')
print("Model saved to house_price_model.joblib")

Run this script from your terminal:

python train_model.py

After running it, you will see a new file named `house_price_model.joblib` in the same directory. This file contains all the "learning" of our model. This is the asset we'll use in our web app.

Step 2: Setting Up the Django Project 🏗️

Now, let's create the skeleton of our web application.

Commands to Run

In your terminal, run these commands one by one:

# 1. Create a new Django project called 'ml_project'
django-admin startproject ml_project

# 2. Navigate into the new project directory
cd ml_project

# 3. Create a new Django app within the project called 'predictor'
python manage.py startapp predictor

Your directory should now look something like this:

ml_project/
├── manage.py
├── ml_project/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── ...
└── predictor/
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── tests.py
    └── views.py

Finally, move the `house_price_model.joblib` file you created in Step 1 into the `predictor` app directory.

Step 3: Creating The View (The Application Brains) 🧠

A "view" in Django is a Python function that takes a web request and returns a web response. This is where we'll load our model and perform the prediction.

Editing `predictor/views.py`

Open the file `predictor/views.py` and replace its contents with this code:

from django.shortcuts import render
import joblib
import numpy as np

# Load the model from the file
model = joblib.load('./predictor/house_price_model.joblib')

def predict(request):
    result = None
    # Check if the request is a POST request (i.e., form submitted)
    if request.method == 'POST':
        # Get the 'size' from the POST data
        size_sqft = request.POST.get('size', '')
        
        try:
            size_sqft = float(size_sqft)
            # Reshape the data for the model (it expects a 2D array)
            prediction_input = np.array([[size_sqft]])
            
            # Use the loaded model to make a prediction
            predicted_price = model.predict(prediction_input)[0]
            
            # Format the result for display
            result = f"Estimated Price: ${predicted_price:.2f}k"
        except (ValueError, TypeError):
            result = "Invalid input. Please enter a valid number."

    # Render the HTML page, passing the result to it
    return render(request, 'predictor/index.html', {'result': result})
Key Concept: The Request-Response Cycle. When you first visit the page, it's a `GET` request, and we just show the form. When you submit the form, it's a `POST` request. Our code checks for this, grabs the user's input, runs the prediction, and then re-renders the same page but now with a result to display.
Step 4: Building The Template (The Application Face) 🖥️

This is the HTML that the user will see and interact with.

First, create the necessary directories. Inside your `predictor` app folder, create a folder named `templates`, and inside that, another folder named `predictor`.

# From inside the ml_project directory
mkdir -p predictor/templates/predictor

Now, create a file inside that new directory called `index.html` and add this code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>House Price Predictor</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h1>🏡 House Price Predictor</h1>
            </div>
            <div class="card-body">
                <p class="card-text">Enter the size of the house in square feet to get an estimated price.</p>
                
                <!-- The Form -->
                <form action="" method="post">
                    <!-- Django security token -->
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="size" class="form-label">Size (sqft):</label>
                        <input type="number" class="form-control" id="size" name="size" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Predict Price</button>
                </form>
            </div>

            <!-- Display the result if it exists -->
            {% if result %}
            <div class="card-footer">
                <div class="alert alert-success mt-3">
                    <h4>{{ result }}</h4>
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</body>
</html>
Step 5: Wiring Up The URLs (The Application Address) 🔌

We need to tell Django which view to run for which URL. This is a two-step process.

1. Main Project URLs (`ml_project/urls.py`)

First, open `ml_project/urls.py` and tell it to include the URLs from our `predictor` app.

from django.contrib import admin
from django.urls import path, include # Make sure to import 'include'

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('predictor.urls')), # Add this line
]
2. Predictor App URLs (`predictor/urls.py`)

This file doesn't exist yet, so create a new file named `urls.py` inside your `predictor` app directory. Add the following code:

from django.urls import path
from . import views

urlpatterns = [
    # When the root URL is visited, run the 'predict' view function
    path('', views.predict, name='predict'),
]
Step 6: Run The Server & Test! 🚀

Everything is now in place! Go to your terminal (make sure you're in the `ml_project` directory where `manage.py` is) and run the development server:

python manage.py runserver

You should see output indicating the server is running. Now, open your web browser and go to this address:

http://127.0.0.1:8000/

You will see your web form. Enter a number like `2200` into the size field and click "Predict Price". The page will reload, and you should see the prediction displayed below the form!

Congratulations! You're a Full-Stack Data Scientist! 🏆

You have successfully bridged the gap between machine learning and web development. This is a critical skill in the industry. You took a model trained in a Python script and deployed it inside a robust web framework, making it accessible and interactive.

You learned to:


This pattern is the foundation for deploying all kinds of machine learning models on the web. You can now build on this to create more complex and powerful AI-driven applications!