Using Django Framework For Making Exciting Data Science Projects – An Example Use Case

Aryan Garg 03 Dec, 2021 ‚ÄĘ 6 min read

This article was published as a part of the Data Science Blogathon.


In this article, I will explain to you how will we use Django Framework for creating some really exciting data science projects in Windows Machine. I will show you the complete procedure to create a website and also integrate a machine learning model into it. This website is used to check the quality of the Wine by providing some parameters.

Now, let’s talk something about Django, it is basically used to code the backend of a webpage and it is written in Python Programming language. This is used for fast website development, due to its huge support of python libraries. It was created by experienced developers to take care of most of the pain of the development of the website, allowing you to focus on building your app instead of reinventing the wheel. Django is free of cost and also available open-source.

Table of Contents

1. How to make a virtual environment and use it in our project?

2. How to set up the Django backend for our project?

3. Training the machine learning model

4. Creating an application for that model

5. How to create the URL for our project (final output)

6. How to add the HTML templates to our application?

7. How to use CSS and apply images?

8. Finalizing the changes in our application

Let’s get started, ūüėÄ

Creating a Virtual Environment

We will firstly set up the Virtual Environment, by running that command in your windows command prompt-

1. Install Virtualenv (run the following command to install the virtual environment)

$ pip install virtualenv

2. Creating an environment (run the following command to create the virtual environment)

$ py -m venv DjangoMLProject

3. Activate it using that command (run the following command to activate that environment)

$ DjangoMLProjectScriptsactivate.bat

4. You can also deactivate it using (run the following command if you want to deactivate that environment)

$ deactivate

Setting Up Django Framework

Now, we will see how to set up the Django framework for our project:

Firstly installing Django using pip within your virtual environment.

But be ensure that your virtual environment is activated.

$ py -m pip install Django

Creating your first Django project:

$ django-admin startproject WineMLProject

Now, move inside the WineMLProject directory and this type of directory structure appears to you:


To verify that everything is working fine, you can also start the development server:

$ python runserver

The output of the command prompt will look like this:

Watching for file changes with StatReloader
Performing system checks…
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, content types, sessions.
Run ‘python migrate’ to apply them.
November 25, 2021 – 16:41:20
Django version 3.1.5, using settings ‘WineMLProject.settings’
Starting development server at
Quit the server with CTRL-BREAK.

Training Machine Learning Model

Create a directory named as ML_Model/ in the main directory. Also, here we have another directory, named ML_Model/ directory that creates a python file named and pastes the following code given below. This file is used for training our model.

Also, download the file named data.csv from my GitHub link and paste it into the same directory. This file contains the data that will be used further for training.

Understanding Technicalities in our Machine Learning Model:

Import necessary libraries: Firstly, we import all the necessary libraries required to do the data processing (Pandas), make manipulations with matrix (Numpy), import machine learning model directly (Scikit-learn), etc.

Machine Learning algorithm: Here, we have used the Random Forest Machine learning algorithm, which gives better accuracy in terms of testing data. If you want to learn about the Random Forest algorithm, you can refer to the link given below.

Understanding Random Forest Regression in a detailed manner

Cross-Validation: Here we have used the stratified shuffle split technique for performing cross-validation, which is inbuilt in the sci-kit-learn. It is used mostly since it will resolve the problem of class biases while we split the given dataset into train and test split.

Finally, after the cross-validation, we can easily find the best accuracy from all the accuracies and that can be used for the final model formation, which we will be deploying on the server.

# These libraries are used by the machine learning model.

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.model_selection import StratifiedShuffleSplit

from sklearn.ensemble import RandomForestRegressor

import joblib

# This is the data file, you can download this file from the github link provided.


print("Dataset Loaded...")

# Performing train test split with stratified shuffle split.

train_set, test_set = train_test_split(wine, test_size=0.2, random_state=42)

split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)

for train_index, test_index in split.split(wine, wine['Alchohol']):

strat_train_set = wine.loc[train_index]

strat_test_set = wine.loc[test_index]

wine = strat_train_set.copy()

wine = strat_train_set.drop("Wine", axis=1)

wine_labels = strat_train_set["Wine"].copy()

# Random Forest Regressor is used for prediction.

model = RandomForestRegressor(), wine_labels)

print("Model Training Ends...")

test_features=strat_test_set.drop("Wine", axis=1)






for i in range(len(test_labels)):

if x[i]>y[i]:




joblib.dump(model, "rf_model.joblib")

print("Model Saved...")


print("Final Accuracy of the Model: ", acc)

The ML Model will be saved in your ML_Model/ directory, and this will look like this.


Creating New App

Now creating a separate app, in which we can start doing our work.

Write this command in your cmd, but be sure you must be in the main working directory.

$ python startapp WineApp

This will create a separate app, WineApp which looks like the following:


Now, inside your WineApp directory, create a directory named templates this will store all HTML Templates, also create a directory named static that stores all static files like CSS/Javascript and Images.

Then, paste the following code into your file.

# These libraries are used by Django for rendering your pages.

from django.http import HttpResponse

from django.shortcuts import render, redirect

import joblib

loaded_rf_model = joblib.load("ML_Model/rf_model.joblib")

def index(request):

if request.method == 'POST':

# These are all the variables that we obtained from the user through a POST Request.




























# Now, predicting the quality of wine based on our parameters.

our_labels = loaded_rf_model.predict(labels)

if our_labels[0]<=400:

wine_quality="A Poor Quality Wine"

if 400<our_labels[0]<=800:

wine_quality="A Average Quality Wine"

if 800<our_labels[0]<=1200:

wine_quality="A Good Quality Wine"

if 1200<our_labels[0]<=1500:

wine_quality="A Exclusive Wine"

if our_labels[0]>1500:

wine_quality="A Premium & Fresh Wine"





# Now rendering our results page with the data.

return render(request,"results.html",details)

return render(request,"index.html")

Now, go to WineMLProject/ and follow that commands.

Register your templates/ directory inside the TEMPLATES, as shown in the figure below.

 Using Django Framework For Making Exciting Data Science Projects

Register your app in the INSTALLED_APPS, as shown in the figure below.

Creating a new app

Finally, paste this code to register the static/ directory.

import os
STATIC_ROOT=  os.path.join(BASE_DIR, 'WineApp/static')
STATIC_URL = '/static/'

Creating URLs

Go to WineMLProject/ and paste that code. Also, be sure to remove all the code that is previously written in it.

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('', include('WineApp.urls')),

Now, go to WineApp/ directory, and create a file again named and copy the following code in it.

The above code will manage the URLs of your main webpage and the file created in WineApp/ directory will manage the URLs of your separate app.

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name="index")

Adding HTML Templates

Inside your WineApp/templates/ directory create a HTML file named as index.html. This will contain your main index page which will be rendered first to the user.

Secondly, in the same directory, create an HTML file named results.html. On this page, the results of the quality of wine will be shown.

You can download both files index.html and results.html from my GitHub Repo.

Adding CSS & Images

Now inside your WineApp/static folder, copy the images and CSS files that are given in my GitHub Repo.

Finalizing the changes in our website

Finally, run that command in your command prompt to migrate all your changes.

$ python migrate

Damm! You have created your first data science web app. Now you can run your app by starting the server.

$ python runserver

This completes our today’s discussion on the project which involves Django, HTML, CSS with machine learning, and finally, we are come up with one of the exciting Data Science projects.


Here is my Linkedin profile in case you want to connect with me. I’ll be happy to be connected with you.

Github Link

Here is my Github profile to find the complete code which I have used in this article.

End Notes

Thanks for reading!

I hope that you have enjoyed the article. If you like it, share it with your friends also. Something not mentioned or want to share your thoughts? Feel free to comment below And I’ll get back to you.

The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion


Aryan Garg 03 Dec 2021

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers


Related Courses
0 Hrs 36 Lessons

Top Data Science Projects for Analysts and Data Scientists


  • [tta_listen_btn class="listen"]