A practical, step-by-step tutorial on integrating a machine learning model with the Django web framework.
You've learned the theory, built models, and understood the statistics. Now it's time for the most exciting part: making your model accessible to the world! A model is only useful if people can interact with it. A web application is the most common way to do this.
In this tutorial, we will take our simple **House Price Predictor** model from the first tutorial and build a Django web app around it. A user will be able to enter a house size into a web form and get an instant price prediction.
Our plan involves two major phases: first, preparing our model, and second, building the web interface to use it.
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
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.
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.
Now, let's create the skeleton of our web application.
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.
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.
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})
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>
We need to tell Django which view to run for which URL. This is a two-step process.
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
]
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'),
]
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:
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!
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!