Building Machine Learning Application with Jingo

by SkillAiNest

Building Machine Learning Application with JingoBuilding Machine Learning Application with Jingo
Photo by Author | Chat GPT

Machine learning has powerful applications in various domains, but effectively deploying the machine learning model in real -world scenarios is often required to use the web framework.

ZiangoA high -level web framework for Azigar, especially known for creating expanding and secure web applications. When the folded with the libraries to be made SkateJiango enables developers to serve the machine learning model through APIS and also facilitates you to create an intuitive web interface for user interaction with these models.

In this tutorial, you will learn to develop a simple Jiango application that offers predictions from the machine learning model. This phased guide, which starts from the initial model training to APIS, will take you to the whole process.

. 1. Project Setup

We will start by creating a base project structure and installing the desired dependence.

Create a new project directory and move into:

mkdir django-ml-app && cd django-ml-app

Install the desired Packages:

pip install Django scikit-learn joblib

Start a new Jiango Project which is named mlapp And create a new app whose name is predictor:

django-admin startproject mlapp .
python manage.py startapp predictor

Set the template directories for our app’s HTML files:

mkdir -p templates/predictor

After running the above orders, your project folder should look like this:

django-ml-app/
├─ .venv/
├─ mlapp/
│  ├─ __init__.py
│  ├─ asgi.py
│  ├─ settings.py
│  ├─ urls.py
│  └─ wsgi.py
├─ predictor/
│  ├─ migrations/
│  ├─ __init__.py
│  ├─ apps.py
│  ├─ forms.py        <-- we'll add this later
│  ├─ services.py     <-- we'll add this later (model load/predict)
│  ├─ views.py        <-- we'll update
│  ├─ urls.py         <-- we'll add this later
│  └─ tests.py        <-- we'll add this later
├─ templates/
│  └─ predictor/
│     └─ predict_form.html
├─ manage.py
├─ requirements.txt
└─ train.py           <-- Machine learning training script

. 2. Train the machine learning model

Next, we will create a model that our Jiango app will use for predictions. We will work with the Classic Irris Datastate, which is included in the skatelight.

In the Project Route Directory, make a script called Name train.py. It loads the script IRIS datastas and distributes it into training and testing sets. Next, it trains random jungle ratings on training data. After the training was completed, it also saved the trained model with its metadata – including feature names and target labels. predictor/model/ Using the directory Jobblib.

from pathlib import Path
import joblib
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

MODEL_DIR = Path("predictor") / "model"
MODEL_DIR.mkdir(parents=True, exist_ok=True)
MODEL_PATH = MODEL_DIR / "iris_rf.joblib"

def main():
    data = load_iris()
    X, y = data.data, data.target

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

    clf = RandomForestClassifier(n_estimators=200, random_state=42)
    clf.fit(X_train, y_train)

    joblib.dump(
        floatformat:3 ,
        MODEL_PATH,
    )
    print(f"Saved model to  p")

if __name__ == "__main__":
    main()

Run a Training Script:

If everything runs successfully, you should see a message that confirms that the model is saved.

. 3. Create Jiango’s settings

Now that we have our app and training script ready, we need to create Jiango so it knows about our new request and where to find templates.

Open mlapp/settings.py And refresh the following:

  • Register predictor In the app INSTALLED_APPS. It is said to be Jiango to include our customs app to the Project Life Cycle (models, opinions, forms, etc.).
  • Add templates/ I Directory TEMPLATES The layout ensures that Jiango can load HTML templates that are not directly tied to a specific app, as we will make the form later.
  • Set ALLOWED_HOSTS Accepting all hosts during development. This makes it easier to run the project locally without host mistakes.
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

INSTALLED_APPS = (
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "predictor",  # <-- add
)

TEMPLATES = (
    floatformat:3 ,
)

# For dev
ALLOWED_HOSTS = ("*")

. 4. Add URL

With our app’s registered, the next step is that URL routing So users can access our pages and API closing points. Jiango roots through http requests to come urls.py Files

We will create two sets of routes:

  1. Project Level URL (mlapp/urls.pyJes – Includes the World Way and the Lord’s Way like Admin Panel predictor App
  2. App Level URL (predictor/urls.pyJes – Defines specific routes for our web form and API.

Open MLAPP/URLS.PY And update it as the following:

# mlapp/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = (
    path("admin/", admin.site.urls),
    path("", include("predictor.urls")),  # web & API routes
)

Create a new file now Forecast/URLS.PY And specify specific routes related to the app:

# predictor/urls.py
from django.urls import path
from .views import home, predict_view, predict_api

urlpatterns = (
    path("", home, name="home"),
    path("predict/", predict_view, name="predict"),
    path("api/predict/", predict_api, name="predict_api"),
)

. 5. Create the form

We need an input form to interact with our model through the web interface where they can enter the flower measurement (Apple and petal dimensions). Jiango makes it easier through his built -in forms module.

We will create a simple form class to obtain the four -digit inputs needed through the IRIS rating.

In you Forecast/ App, create a new file that says Forms.py And add the following code:

# predictor/forms.py
from django import forms

class IrisForm(forms.Form):
    sepal_length = forms.FloatField(min_value=0, label="Sepal length (cm)")
    sepal_width  = forms.FloatField(min_value=0, label="Sepal width (cm)")
    petal_length = forms.FloatField(min_value=0, label="Petal length (cm)")
    petal_width  = forms.FloatField(min_value=0, label="Petal width (cm)")

. 6. Load the model and predict

Now that we have trained and saved our Iris rankings, we need a path for the Jiango app Load the model And use it for predictions. We will keep things organized, we will keep all predicted logic within a dedicated Services.py I file predictor App

This ensures that our views are clean and focus on application/response handling, while the prophecy logic remains in a re -usable service module.

I Petition/ServicesAdd the following code:

# predictor/services.py
from __future__ import annotations
from pathlib import Path
from typing import Dict, Any
import joblib
import numpy as np

_MODEL_CACHE: Dict(str, Any) = {}

def get_model_bundle():
    """
    Loads and caches the trained model bundle:
    {
      "estimator": RandomForestClassifier,
      "target_names": ndarray(str),
      "feature_names": list(str),
    }
    """
    global _MODEL_CACHE
    if "bundle" not in _MODEL_CACHE:
        model_path = Path(__file__).resolve().parent / "model"
        _MODEL_CACHE("bundle") = joblib.load(model_path)
    return _MODEL_CACHE("bundle")

def predict_iris(features):
    """
    features: list(float) of length 4 (sepal_length, sepal_width, petal_length, petal_width)
    Returns dict with class_name and probabilities.
    """
    bundle = get_model_bundle()
    clf = bundle("estimator")
    target_names = bundle("target_names")

    X = np.array((features), dtype=float)
    proba = clf.predict_proba(X)(0)
    idx = int(np.argmax(proba))
    return {
        "class_index": idx,
        "class_name": str(target_names(idx)),
        "probabilities": {str(name): float(p) for name, p in zip(target_names, proba)},
    }

. 7. ideas

Welfare Work as glue between user inputs, models, and final reactions (HTML or JSON. At this stage, we will prepare three opinions:

  1. House – offers the appearance of predictions.
  2. Forecasting_wyo – Handle form requests from web interface.
  3. Forecasting_p – JSON API offers closing point for program predictions.

I Forecast/theoryAdd the following code:

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt  # <-- add
from .forms import IrisForm
from .services import predict_iris
import json


def home(request):
    return render(request, "predictor/predict_form.html", {"form": IrisForm()})


@require_http_methods(("POST"))
def predict_view(request):
    form = IrisForm(request.POST)
    if not form.is_valid():
        return render(request, "predictor/predict_form.html", {"form": form})
    data = form.cleaned_data
    features = (
        data("sepal_length"),
        data("sepal_width"),
        data("petal_length"),
        data("petal_width"),
    )
    result = predict_iris(features)
    return render(
        request,
        "predictor/predict_form.html",
        {"form": IrisForm(), "result": result, "submitted": True},
    )


@csrf_exempt  # <-- add this line
@require_http_methods(("POST"))
def predict_api(request):
    # Accept JSON only (optional but recommended)
    if request.META.get("CONTENT_TYPE", "").startswith("application/json"):
        try:
            payload = json.loads(request.body or "{}")
        except json.JSONDecodeError:
            return JsonResponse({"error": "Invalid JSON."}, status=400)
    else:
        # fall back to form-encoded if you want to keep supporting it:
        payload = request.POST.dict()

    required = ("sepal_length", "sepal_width", "petal_length", "petal_width")
    missing = (k for k in required if k not in payload)
    if missing:
        return JsonResponse({"error": f"Missing: {', '.join(missing)}"}, status=400)

    try:
        features = (float(payload(k)) for k in required)
    except ValueError:
        return JsonResponse({"error": "All features must be numeric."}, status=400)

    return JsonResponse(predict_iris(features))

. 8. Template

Finally, we will create an HTML template that works for the user interface for our IRIS prediction.

This template will:

  • Offer the Jiango Farm Fields that we have mentioned earlier.
  • Provide a clean, styled layout with the accountable form input.
  • Show the results in the forecast when available.
  • Mention the API closing point for developers that prefer access to programs.








Iris Predictor












Enter Iris flower measurements to get a prediction.

{% csrf_token %}

{{ form.sepal_length }}

{{ form.sepal_width }}

{{ form.petal_length }}

{{ form.petal_width }}

{% if submitted and result %}
Predicted class: {{ result.class_name }}
Probabilities:
    {% for name, p in result.probabilities.items %}
  • {{ name }}: {{ p|floatformat:3 }}
  • {% endfor %}
{% endif %}

API available at POST /api/predict/

. 9. Run the application

With everything, it is time for us to run our Jingo Project and test both the web form and the API closing point.

Run the following command to configure the default Jiango Database (for Admin, Sessions, etc.):

Launch Jiango Development Server:

python manage.py runserver

If everything has been configured correctly, you will see a similar output:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
September 09, 2025 - 02:01:27
Django version 5.2.6, using settings 'mlapp.settings'
Starting development server at 
Quit the server with CTRL-BREAK.

Open your browser and visit: to use web form interface.

Building Machine Learning Application with JingoBuilding Machine Learning Application with Jingo

Building Machine Learning Application with JingoBuilding Machine Learning Application with Jingo

You can also send a post request to API using Curl:

curl -X POST api/predict/ \
  -H "Content-Type: application/json" \
  -d '{"sepal_length":5.1,"sepal_width":3.5,"petal_length":1.4,"petal_width":0.2}'

Expected Answer:

{
  "class_index": 0,
  "class_name": "setosa",
  "probabilities": {
    "setosa": 1.0,
    "versicolor": 0.0,
    "virginica": 0.0
  }
}

. 10.

Before wrapped up, it is a good process to confirm that our application works as expected. Jiango provides a built -in Testing framework Which is integrated with azigar unittest Module

We will make some easy tests to ensure:

  1. Home Page Raders Correctly and includes the title.
  2. API end point Return a correct response to the prediction.

I predictor/tests.pyAdd the following code:

from django.test import TestCase
from django.urls import reverse

class PredictorTests(TestCase):
    def test_home_renders(self):
        resp = self.client.get(reverse("home"))
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "Iris Predictor")

    def test_api_predict(self):
        url = reverse("predict_api")
        payload = {
            "sepal_length": 5.0,
            "sepal_width": 3.6,
            "petal_length": 1.4,
            "petal_width": 0.2,
        }
        resp = self.client.post(url, payload)
        self.assertEqual(resp.status_code, 200)
        data = resp.json()
        self.assertIn("class_name", data)
        self.assertIn("probabilities", data)

Run the following command in your terminal:

You should see the same output like this:

Found 2 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.758s
                                                                                
OK
Destroying test database for alias 'default'...

With the passage of these tests, you may be confident that your Jiango + machine learning app is working properly from end to end.

. Abstract

You have successfully created a complete machine learning application using the Jiango Framework, which has brought all the components into a functional system simultaneously.

Training and saving a model, you integrated it into Jiango Services to make predictions. You have also created a clean web form for the user input and exposed JSON API for programming access. In addition, you imposed automatic tests to ensure that the application runs reliably.

Although this project has focused on the IRIS dataset, the same structure can be extended to adjust the more complex models, large datases, or even production APIS, which makes it a solid foundation of real -world machine learning applications.

Abid Ali Owan For,,,,,,,,,, for,, for,,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,, for,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,,, for,,, for,,, for,,, for,,, for,,,, for,,, for,,,,, for,,, for,,, for,,, for,,, for,.@1abidaliawan) A certified data scientist is a professional who loves to create a machine learning model. Currently, he is focusing on creating content and writing technical blogs on machine learning and data science technologies. Abid has a master’s degree in technology management and a bachelor’s degree in telecommunications engineering. Its vision is to create AI products using a graph neural network for students with mental illness.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro