AI Model Deployment with Django

I’ve been working as a Python developer for many years, and one of the most rewarding experiences has been deploying AI models into real-world applications. While creating machine learning models is exciting, making them accessible to users through a web app is where the magic happens.

Django makes it simple to deploy your AI models. In this guide, I’ll walk you through the entire process of deploying an AI model with Django, sharing tips and code examples based on my firsthand experience.

Let’s get started!

Methods to Use Django for AI Model Deployment

Django is designed for rapid development and clean, pragmatic design. It handles everything from URL routing to database management, allowing you to focus on your AI logic. Plus, it’s scalable and secure, making it a great choice for production-ready AI applications.

Read Add Google reCAPTCHA to Django Form

Method 1: Deploy AI Model by Loading a Pickled Model in Django

The most common way to deploy an AI model is by training it offline, saving it as a file (usually with pickle or joblib), and then loading it in your Django app to make predictions.

Step 1: Train and Save Your AI Model

Here’s a simple example using scikit-learn to train a model predicting housing prices in the USA based on features like square footage and number of bedrooms.

# train_model.py
import pandas as pd
from sklearn.linear_model import LinearRegression
import joblib

# Sample dataset (replace with your real data)
data = {
    'sqft': [1500, 1800, 2400, 3000, 3500],
    'bedrooms': [3, 4, 3, 5, 4],
    'price': [400000, 500000, 600000, 650000, 700000]
}
df = pd.DataFrame(data)

X = df[['sqft', 'bedrooms']]
y = df['price']

model = LinearRegression()
model.fit(X, y)

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

Run this script once to create the house_price_model.pkl file.

Step 2: Set Up a Django Project and App

Create a new Django project and app:

django-admin startproject ai_deploy
cd ai_deploy
python manage.py startapp predictor

Add 'predictor' to your INSTALLED_APPS in settings.py.

Read Create a Contact Form with Django and SQLite

Step 3: Load the Model in Django

Create a utility module in your app to load the model once:

# predictor/ml_model.py
import joblib
import os

MODEL_PATH = os.path.join(os.path.dirname(__file__), 'house_price_model.pkl')

model = joblib.load(MODEL_PATH)

def predict_price(sqft, bedrooms):
    features = [[sqft, bedrooms]]
    prediction = model.predict(features)
    return prediction[0]

Copy the house_price_model.pkl file into the predictor app directory.

Step 4: Create Views and Templates

Set up a simple form where users can input home features to get a price prediction.

# predictor/views.py
from django.shortcuts import render
from .ml_model import predict_price

def home(request):
    price = None
    if request.method == 'POST':
        sqft = float(request.POST.get('sqft'))
        bedrooms = int(request.POST.get('bedrooms'))
        price = predict_price(sqft, bedrooms)
    return render(request, 'predictor/home.html', {'price': price})

Create a template predictor/templates/predictor/home.html:

<!DOCTYPE html>
<html>
<head>
    <title>House Price Predictor</title>
</head>
<body>
    <h1>Predict House Price</h1>
    <form method="post">
        {% csrf_token %}
        <label for="sqft">Square Footage:</label>
        <input type="number" name="sqft" step="any" required><br><br>
        <label for="bedrooms">Bedrooms:</label>
        <input type="number" name="bedrooms" required><br><br>
        <button type="submit">Predict</button>
    </form>

    {% if price %}
        <h2>Estimated Price: ${{ price|floatformat:2 }}</h2>
    {% endif %}
</body>
</html>

Step 5: Configure URLs

# ai_deploy/urls.py
from django.contrib import admin
from django.urls import path
from predictor import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
]

Step 6: Run Your Django Server

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser, enter the square footage and bedrooms, and get your price prediction.

You can see the output in the screenshot below.

tensorflow Django

Check out Build a Django Contact Form with Email

Method 2: Deploy AI Model Using Django REST Framework (API Approach)

If you want your AI model to be accessed programmatically (e.g., from a mobile app or JavaScript front-end), you can build an API with Django REST Framework.

Step 1: Install Django REST Framework

pip install djangorestframework

Add 'rest_framework' to INSTALLED_APPS in settings.py.

Step 2: Create an API View

# predictor/api_views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .ml_model import predict_price

@api_view(['POST'])
def predict_api(request):
    sqft = float(request.data.get('sqft'))
    bedrooms = int(request.data.get('bedrooms'))
    price = predict_price(sqft, bedrooms)
    return Response({'predicted_price': price})

Step 3: Add API URL

# ai_deploy/urls.py
from django.urls import path
from predictor import api_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('predict/', api_views.predict_api, name='predict_api'),
]

Step 4: Test the API

You can test this with curl or Postman:

curl -X POST http://127.0.0.1:8000/predict/ -H "Content-Type: application/json" -d '{"sqft": 2000, "bedrooms": 4}'

You’ll get a JSON response with the predicted price.

Read How to Use Python Django pre_save

Tips from My Experience

  • Model Loading: Load the model once at server start, not on every request, to improve performance.
  • Security: Always validate and sanitize user inputs.
  • Versioning: Keep track of your model versions and update the deployed model carefully.
  • Scaling: For heavy loads, consider deploying your AI model separately (e.g., with Flask or FastAPI) and have Django communicate via API calls.
  • Testing: Write unit tests for your prediction functions and API endpoints.

Deploying AI models with Django combines the power of Python’s ML ecosystem with a robust web framework. The two methods I shared cover most use cases, from simple web forms to REST APIs.

Give it a try with your models and data. You’ll be surprised how quickly you can turn your AI experiments into usable applications.

If you want to dive deeper into Django or AI deployment, I recommend exploring more tutorials and examples to build on this foundation.

You may read other Django-related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.