0% found this document useful (0 votes)
66 views35 pages

3rd Review

The document summarizes a master's thesis project on developing a web application for online shopping. It discusses the programming languages, tools, and database used in the project. Python, Django framework, Mezzanine CMS, PyCharm IDE, Anaconda environment, and SQLite database were used. The document then describes the objectives, technologies used including HTML, CSS, Bootstrap, React JS, and Django for the frontend and backend. It provides details on Django and how it follows the MVT architecture and promotes reusability and portability. The methodology of model-view-template is explained along with an example of how Django code is structured with URL mappings and views.

Uploaded by

Manasvi Gautam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views35 pages

3rd Review

The document summarizes a master's thesis project on developing a web application for online shopping. It discusses the programming languages, tools, and database used in the project. Python, Django framework, Mezzanine CMS, PyCharm IDE, Anaconda environment, and SQLite database were used. The document then describes the objectives, technologies used including HTML, CSS, Bootstrap, React JS, and Django for the frontend and backend. It provides details on Django and how it follows the MVT architecture and promotes reusability and portability. The methodology of model-view-template is explained along with an example of how Django code is structured with URL mappings and views.

Uploaded by

Manasvi Gautam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

School of Information Technology & Engineering

Department of Computer Application

Fall Semester 2022-‘23

ITA6099 – Master Thesis

Third Review Report

Reg. No: 21MCA0039


Student Name: Manaswi Gautam
Guide Name: Dr. Neelu Khare
Master Thesis Title: Off Campus Internship ( Web Development Intern)

Programming Languages/ Tools / DBMS Used for Implementation:


1. Languages/Technologis
 Python
 Django (FrameWork)
 Mezzanine(Content Management System)

2. Tools:
 Pycharm(Code editor)
 Anaconda(creating the enviourment)
 Python IDE
 GitBash Terminal
 Any Browser(Server Connection)
3. DBMS Used for Implementation:

SQLite database which comes by default with Django.


ABILITY TO ARTICULATE THE PROBLEM AND IDENTIFY
OBJECTIVES

The Company works on mainly web based Applications under which they have different
department. In my Internship, they are giving me the training for Django as a Backend
Developer. The project they have initially assigned me is related to a shopping Web
Application in which they have two parts one which is used by the customer that is called
front-end and the second one is admin part where all the activities will be monitories, for both
these parts the backend will be designed by me. The basic output of these project will be a
web based application which will be used by the clients for their online shopping purpose.

TECHNOLOGY USED TO ACHIEVE THE IDENTIFIED


OBJECTIVES-
For this project, till now we have used HTML, CSS, Bootstrap, and React JS for the frontend
part and for backend part we are using Django, Python and in future we will use more
technologies. I am working on backend using Django and I am also using React JS for
linking it with code.

Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. Built by experienced developers, it takes care of much of the hassle of web
development, so you can focus on writing your app without needing to reinvent the wheel.
It’s free and open source

The main Technologies used are:


 Python
 Django (FrameWork)
 Mezzanine(Content Management System)

As my projects in the company are mainly based on web development me and my team worked
on python web based development. Python has some distinct advantages that make it suitable
for developing web applications. Python has a large number of ready-made libraries for
developers to use to solve numerous problems; developers can distribute their libraries as well.
All these things allow developers to not focus on issues that are already solved but to use their
time and energy to build applications and solve problems that are unique to them.
There are mainly two framework which is popular for Python web based development:

1. Django
2. Flask
I have mainly used Django with mezzanine for development of Web-server based applications
and websites.
About Django :

Complete
Django follows the "Batteries included" philosophy and provides almost everything
developers might want to do "out of the box". Because everything you need is part of the one
"product", it all works seamlessly together, follows consistent design principles, and has
extensive and up-to-date documentation.

Versatile
Django can be (and has been) used to build almost any type of website — from content
management systems and wikis, through to social networks and news sites. It can work with
any client-side framework, and can deliver content in almost any format (including HTML,
RSS feeds, JSON, and XML).
Internally, while it provides choices for almost any functionality you might want (e.g. several
popular databases, templating engines, etc.), it can also be extended to use other components
if needed.
Secure
Django helps developers avoid many common security mistakes by providing a framework
that has been engineered to "do the right things" to protect the website automatically. For
example, Django provides a secure way to manage user accounts and passwords, avoiding
common mistakes like putting session information in cookies where it is vulnerable (instead
cookies just contain a key, and the actual data is stored in the database) or directly storing
passwords rather than a password hash.

A password hash is a fixed-length value created by sending the password through a


cryptographic hash function. Django can check if an entered password is correct by running it
through the hash function and comparing the output to the stored hash value. However due to
the "one-way" nature of the function, even if a stored hash value is compromised it is hard for
an attacker to work out the original password.

Django enables protection against many vulnerabilities by default, including SQL injection,
cross-site scripting, cross-site request forgery and click jacking

Scalable
Django uses a component-based "shared-nothing" architecture (each part of the architecture is
independent of the others, and can hence be replaced or changed if needed). Having a clear
separation between the different parts means that it can scale for increased traffic by adding
hardware at any level: caching servers, database servers, or application servers. Some of the
busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and
Disqus).

Maintainable
Django code is written using design principles and patterns that encourage the creation of
maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself
(DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django
also promotes the grouping of related functionality into reusable "applications" and, at a
lower level, groups related code into modules (along the lines of the Model View Controller
(MVC) pattern).
Portable
Django is written in Python, which runs on many platforms. That means that you are not tied
to any particular server platform, and can run your applications on many flavors of Linux,
Windows, and macOS.
Furthermore, Django is well-supported by many web hosting providers, who often provide
specific infrastructure and documentation for hosting Django sites.

Methodology used:
We follows the Model-View-Template (MVT) variation of the MVC pattern, where the
Template component is responsible for defining the layout of the user interface. The MVT
pattern separates an application into three distinct components:
• Model: The Model component represents the data and business logic of the
application. Django uses an Object-Relational Mapping (ORM) system that allows
developers to define the data models using Python classes. The ORM system then
translates these classes into database tables.
• View: The View component handles the user input and output. In Django, views are
Python functions that take HTTP requests and return HTTP responses. Views interact
with the Model to retrieve or update data and pass the data to the Template for
rendering.
• Template: The Template component defines the layout of the user interface. Django
uses its own templating language that allows developers to define the HTML markup
and control flow logic of the user interface. The Template receives data from the
View and renders it into an HTML response.
Figure 1(Methodolgy)
What does Django code look like?
In a traditional data-driven website, a web application waits for HTTP requests from the web
browser (or other client). When a request is received the application works out what is needed
based on the URL and possibly information in POST data or GET data. Depending on what is
required it may then read or write information from a database or perform other tasks
required to satisfy the request. The application will then return a response to the web browser,
often dynamically creating an HTML page for the browser to display by inserting the
retrieved data into placeholders in an HTML template.

 URLs: While it is possible to process requests from every single URL via a single
function, it is much more maintainable to write a separate view function to handle
each resource. A URL mapper is used to redirect HTTP requests to the appropriate
view based on the request URL. The URL mapper can also match particular patterns
of strings or digits that appear in a URL and pass these to a view function as data.

Workingof Django:

Sending the request to the right view (urls.py)

A URL mapper is typically stored in a file named urls.py. In the example below, the mapper
(URL patterns) defines a list of mappings between routes (specific URL patterns) and
corresponding view functions. If an HTTP Request is received that has a URL matching a
specified pattern, then the associated view function will be called and passed the request.

urlpatterns = [
path('admin/', admin.site.urls),
path('book/<int:id>/', views.book_detail, name='book_detail'),
path('catalog/', include('catalog.urls')),
re_path(r'^([0-9]+)/$', views.best),
]

The urlpatterns object is a list of path () and/or re_path () functions (Python lists are defined
using square brackets, where items are separated by commas and may have an optional
trailing comma. For example: [item1, item2, item3,]).
The first argument to both methods is a route (pattern) that will be matched.
The path() method uses angle brackets to define parts of a URL that will be captured and
passed through to the view function as named arguments. The re_path () function uses a
flexible pattern matching approach known as a regular expression.

The second argument is another function that will be called when the pattern is matched. The
notation views.book_detail indicates that the function is called book_detail () and can be
found in a module called views (i.e. inside a file named views.py)

Handling the request (views.py)

Views are the heart of the web application, receiving HTTP requests from web clients and
returning HTTP responses. In between, they marshal the other resources of the framework to
access databases, render templates, etc.

The example below shows a minimal view function index (), which could have been called
by our URL mapper in the previous section. Like all view functions it receives an Http
Request object as a parameter (request) and returns an Http Response object. In this case we
don't do anything with the request, and the response returns a hard-coded string.

# filename: views.py (Django view functions)

from django.http import HttpResponse

def index(request):
# Get an HttpRequest - the request parameter
# perform operations using information from the request.
# Return HttpResponse
return HttpResponse('Hello from Django!')

Defining data models (models.py)

Django web applications manage and query data through Python objects referred to as
models. Models define the structure of stored data, including the field types and possibly also
their maximum size, default values, selection list options, help text for documentation, label
text for forms, etc. The definition of the model is independent of the underlying database —
we can choose one of several as part of your project settings. Once ywe chosen what database
we want to use, we don't need to talk to it directly at all — we just write our model structure
and other code, and Django handles all the "work" of communicating with the database.

COMPARING RELATED TECHNOLOGIES THAT CAN BE USED TO


REALIZE THE IDENTIFIED OBJECTIVES –

The technologies which can be used in place of Django are-

1. Turbogears:

Based on the MVC (Model-View-Controller) design pattern, TurboGears is a full-stack


framework for developing web applications. It is flexible, portable, and comes with a fully
integrated MochiKit JavaScript library.

TurboGears applications can be deployed on any web server that supports the WSGI Python
interface. In addition, it comes attached with Gearbox, a command-line interface for
managing projects, and Kajiki, a templating engine.
It is perfect for handling database-driven websites as it has an open-source SQL kit known as
SQLAlchemy. It also has support for SQLObject, which is a powerful Object-relational
mapping package that lets you write server-side code very quickly, in just a few days.
TurboGears can be considered the best alternative to Django, if you are looking for a
framework that is most similar to Django. Both have powerful template engine, high-powered
ORM, database support, and are extensible, but TurboGears is not as opinionated.

2. Web2py:

Web2py is a web-based framework that allows you to create, modify, deploy and manage
apps from anywhere using your browser. It is a cross-platform framework that can be used on
multiple devices and browsers. It also deploys a powerful error logging and ticketing system.
Web2py has no dependencies outside of the Python standard library. It requires no
prerequisites for installation or configuration. Along with backward compatibility, it also has
security measures against attacks such as cross-site scripting, SQL injection and other
malicious attacks.

It has a fully-featured IDE, which allows you to change the content on your website from any
web browser, even after it is deployed. You can develop fast, scalable, secure database-driven
web applications with Web2py.

3. CubicWeb

CubicWeb is a free, open-source semantic web application framework that works on a data
model. Developers can develop web applications efficiently by reusing components called
cubes. It employs object-oriented design principles and has an embedded query language.

CubicWeb also includes Relational Query Language (RQL) which simplifies data-related
queries using a simple syntax. You are able to manage relationship queries, data repositories,
and view attributes.

CubicWeb offers semi-automatic mechanisms for handling XML and JSON code generation,
and workflow with security. Large-scale semantic websites and linked open data apps are
good for using CubicWeb.

4. Microframework:

Django, can sometimes be monolithic. Other full stack frameworks can also be too complex
for small, basic websites and applications that do not require a lot of features. Python has a
series of well-designed micro frameworks such as Flask, Bottle and CherryPy that work
perfectly with small-scale websites.

Some advantages of using micro-frameworks are –

 Simple, easy to use, lightweight, and small footprint


 URL routing through REST API
 A good choice for small web projects such as static websites or one page applications
 Uses WSGI to work with HTTP request
5. CherryPy:

CherryPy is a python based, object-oriented web development framework. It provides built-in


capital plugins and a powerful configuration system.

CherryPy also includes an implementation of the Ruby programming language framework. It


incorporates the Ruby on Rail’s routing system in Python. You can generate and map URLs
to controllers.

CherryPy requires minimal lines to write the source code resulting in low development time
and high productivity.

It is a very lightweight alternative for Django and one of the oldest Python frameworks.
CherryPy has built-in tools for coding static web pages, URL encoding, user authentication,
and session management. It is also embedded with a powerful configuration system that can
handle multiple HTTP requests and run multiple HTTP servers simultaneously.

6. Pyramid:

Pyramid is the most flexible Python framework available .A lightweight, scalable framework,
Pyramid is used for developing small to large-scale web apps. It is also great for quick
prototyping and for developers who are working on API projects.

Pyramid has a small footprint but it is easily extendable with add-ons, configurations and
libraries to include unique functionalities in your app. It sometimes provides so many options
that it can get tough to make the right choices in a new project.

Major companies such as Dropbox, Fedora, Mozilla, SurveyMonkey, and Yelp use Pyramid
for website development.

7. Bottle:

The bottle is a simple, fast, and lightweight web-based framework distributed as a single file
module. It works on any Python WSGI compliant server and is mainly used for building
APIs. It is also a preferred choice for building simple prototypes.

It has support for various databases and URL parameters along with the built-in template
engine Simple Template. It is also highly flexible and allows you to integrate third-party
templating engines such as Mako, Jinja2, or Cheetah. There are plugins and external libraries
available for ORM support, NoSQL database, and admin panels.

8. Falcon:

Falcon is a reliable, high-performance Python WSGI library for rapid backend development.
It is mainly used for micro web services, Web API, web sockets, and back-ends of large-scale
applications. It encourages usage of REST architectural style, very much like the Django Rest
framework, and tries to do as little as possible.

It is highly effective and cuts down internal dependencies by using a clean HTTP and REST
framework architecture design. High performance with a significantly lower code base,
Falcon is a minimalistic alternative to Django.

Engagement in learning and work:


Project 1: Ecommerce website using Django-
This project deals with developing a Virtual website ‘E-commerce Website’ named E-shop. It
provides the user with a list of the various products available for purchase in the store. For the
convenience of online shopping, a shopping cart is provided to the user. After the selection of the
goods, it is sent for the order confirmation process. The system is implemented using Python’s web
framework Django. I have designed the backend for this project

Scope: The scope of the project will be limited to some functions of the e-commerce website. It
will display products, customers can select catalogs and select products, and can remove products
from their cart specifying the quantity of each item. Selected items will be collected in a cart. At
checkout, the item on the card will be presented as an order. Customers can pay for the items in the
cart to complete an order. This project has great future scope. The project also provides security
with the use of login ID and passwords, so that no unauthorized users can access your account. The
only authorized person who has the appropriate access authority can access the software.

Technologies used in the project:


Django framework and SQLite database which comes by default with Django.

Website Working Flow Diagram:


Figure 2(project Architecture)

High-level flowchart for building the website:


1. Plan and Design:
Identify the requirements and specifications for the e-commerce website.
Design the website’s layout, user interface, and user experience.
2. Set up the Development Environment:
Install Python, Django, and other necessary packages.
Set up a virtual environment for the project.

3. Create the Django Project:


Create a new Django project.
Configure the project settings, database settings, and other configurations.

4. Design the Database:


Design the database schema and create models for the database tables.
Define relationships between the models.

5. Create the Views:


Create views to handle user requests.
Define the logic for each view.

6. Create the Templates:


Create templates to display the views.
Use HTML, CSS, and Django template tags and filters to render the templates.

7. Implement User Authentication:


Add user registration and login functionality.
Implement user authentication and authorization.

8. Implement Product Catalog:


Create a product model and views to display the product catalog.
Implement search and filtering options for the product catalog.

9. Implement Shopping Cart:


Create a shopping cart model and views to add, update, and remove items from the
cart.
10. Implement checkout functionality and payment gateway integration.
Implement Order Management:
Create a model for orders and views to manage orders.
Implement order tracking and fulfillment functionality.
11. Test and Deploy:
Test the website’s functionality and performance.
Deploy the website to a production server.

Step by Step Implementation:


 Step 1- Create Normal Project: Open the IDE and create a normal project by selecting File ->
New Project.

 Step 2-Install Django: Next, we will install the Django module from the terminal. We will
use PyCharm integrated terminal to do this task, to install the module by running python -m
pip install django command

 Step 3-Check Installed Django version: To check the installed Django version, you can run
the python -m django -version command as shown below.

 Step 4-Create Django Project: When we execute django-admin startproject command, then it
will create a Django project inside the normal project which we already have created here.
django-admin startproject ProjectName.

 Step 5-Run Default Django webserver:- Django internally provides a default webserver
where we can launch our applications. python manage.py runserver command in terminal.
By default, the server runs on port 127.0.0. 8000. Access the webserver at the highlighted
URL.

When We run the server the interface will look like this:
When we Open the project folder using a text editor(Pycharm). The directory structure look
like this :

Step 6- Now add store app in E-commerce website in settings.py.


urls.py
This file contains all the URL patterns used by the website

from django.contrib import admin

from django.urls import path, include

from django.conf.urls.static import static

from . import settings

urlpatterns = [

path('admin/', admin.site.urls),

path('', include('store.urls'))

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models
The below screenshot shows the required models that we will need to create. These models are
tables that will be stored in the SQLite database.

Each model and the fields required by each model:

1. category.py

from django.db import models

class Category(models.Model):

name = models.CharField(max_length=50)

@staticmethod

def get_all_categories():

return Category.objects.all()

def __str__(self):

return self.name
2. customer.py

from django.db import models

class Customer(models.Model):

first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=10)
email = models.EmailField()
password = models.CharField(max_length=100)
# to save the data
def register(self):
self.save()

@staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False

def isExists(self):
if Customer.objects.filter(email=self.email):
return True

return False
3. products.py

from django.db import models

from .category import Category

class Products(models.Model):

name = models.CharField(max_length=60)

price = models.IntegerField(default=0)

category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)

description = models.CharField(

max_length=250, default='', blank=True, null=True)

image = models.ImageField(upload_to='uploads/products/')

@staticmethod

def get_products_by_id(ids):

return Products.objects.filter(id__in=ids)

@staticmethod

def get_all_products():
return Products.objects.all()

@staticmethod

def get_all_products_by_categoryid(category_id):

if category_id:

return Products.objects.filter(category=category_id)

else:

return Products.get_all_products()

4. Orders.py:

from django.db import models


from .product import Products
from .customer import Customer
import datetime

class Order(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
address = models.CharField(max_length=50, default='', blank=True)
phone = models.CharField(max_length=50, default='', blank=True)
date = models.DateField(default=datetime.datetime.today)
status = models.BooleanField(default=False)

def placeOrder(self):
self.save()

@staticmethod
def get_orders_by_customer(customer_id):
return Order.objects.filter(customer=customer_id).order_by('-date')

5. Views :

In views, we created a view named home.py, login.py, signup.py, cart.py, checkout.py,


orders.py which takes a request and renders an HTML as a response. After that we created a
home.html, login.html, signup.html, cart.html, checkout.html, orders.html in the templates.
And then map the views to the store\urls.py folder.

from django.contrib import admin

from django.urls import path


from .views.home import Index, store

from .views.signup import Signup

from .views.login import Login, logout

from .views.cart import Cart

from .views.checkout import CheckOut

from .views.orders import OrderView

from .middlewares.auth import auth_middleware

urlpatterns = [

path('', Index.as_view(), name='homepage'),

path('store', store, name='store'),

path('signup', Signup.as_view(), name='signup'),

path('login', Login.as_view(), name='login'),

path('logout', logout, name='logout'),

path('cart', auth_middleware(Cart.as_view()), name='cart'),

path('check-out', CheckOut.as_view(), name='checkout'),

path('orders', auth_middleware(OrderView.as_view()), name='orders'),

]
The below files show the views for each functionality of the site.

home.py:

from django.shortcuts import render, redirect, HttpResponseRedirect

from store.models.product import Products

from store.models.category import Category

from django.views import View

# Create your views here.

class Index(View):

def post(self, request):

product = request.POST.get('product')

remove = request.POST.get('remove')
cart = request.session.get('cart')

if cart:

quantity = cart.get(product)

if quantity:

if remove:

if quantity <= 1:

cart.pop(product)

else:

cart[product] = quantity-1

else:

cart[product] = quantity+1

else:

cart[product] = 1

else:

cart = {}

cart[product] = 1

request.session['cart'] = cart

print('cart', request.session['cart'])

return redirect('homepage')

def get(self, request):

# print()

return HttpResponseRedirect(f'/store{request.get_full_path()[1:]}')
def store(request):

cart = request.session.get('cart')

if not cart:

request.session['cart'] = {}

products = None

categories = Category.get_all_categories()

categoryID = request.GET.get('category')

if categoryID:

products = Products.get_all_products_by_categoryid(categoryID)

else:

products = Products.get_all_products()

data = {}

data['products'] = products

data['categories'] = categories

print('you are : ', request.session.get('email'))

return render(request, 'index.html', data)


1. login.py:

from django.shortcuts import render, redirect, HttpResponseRedirect


from django.contrib.auth.hashers import check_password
from store.models.customer import Customer
from django.views import View

class Login(View):
return_url = None

def get(self, request):


Login.return_url = request.GET.get('return_url')
return render(request, 'login.html')

def post(self, request):


email = request.POST.get('email')
password = request.POST.get('password')
customer = Customer.get_customer_by_email(email)
error_message = None
if customer:
flag = check_password(password, customer.password)
if flag:
request.session['customer'] = customer.id

if Login.return_url:
return HttpResponseRedirect(Login.return_url)
else:
Login.return_url = None
return redirect('homepage')
else:
error_message = 'Invalid !!'
else:
error_message = 'Invalid !!'

print(email, password)
return render(request, 'login.html', {'error': error_message})

def logout(request):
request.session.clear()
return redirect('login')

2. signup.py:
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password
from store.models.customer import Customer
from django.views import View

class Signup (View):


def get(self, request):
return render(request, 'signup.html')

def post(self, request):


postData = request.POST
first_name = postData.get('firstname')
last_name = postData.get('lastname')
phone = postData.get('phone')
email = postData.get('email')
password = postData.get('password')
# validation
value = {
'first_name': first_name,
'last_name': last_name,
'phone': phone,
'email': email
}
error_message = None

customer = Customer(first_name=first_name,
last_name=last_name,
phone=phone,
email=email,
password=password)
error_message = self.validateCustomer(customer)

if not error_message:
print(first_name, last_name, phone, email, password)
customer.password = make_password(customer.password)
customer.register()
return redirect('homepage')
else:
data = {
'error': error_message,
'values': value
}
return render(request, 'signup.html', data)

def validateCustomer(self, customer):


error_message = None
if (not customer.first_name):
error_message = "Please Enter your First Name !!"
elif len(customer.first_name) < 3:
error_message = 'First Name must be 3 char long or more'
elif not customer.last_name:
error_message = 'Please Enter your Last Name'
elif len(customer.last_name) < 3:
error_message = 'Last Name must be 3 char long or more'
elif not customer.phone:
error_message = 'Enter your Phone Number'
elif len(customer.phone) < 10:
error_message = 'Phone Number must be 10 char Long'
elif len(customer.password) < 5:
error_message = 'Password must be 5 char long'
elif len(customer.email) < 5:
error_message = 'Email must be 5 char long'
elif customer.isExists():
error_message = 'Email Address Already Registered..'
# saving
return error_message
3. cart.py:

from django.db import models


from .product import Products
from .customer import Customer
import datetime

class Order(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
address = models.CharField(max_length=50, default='', blank=True)
phone = models.CharField(max_length=50, default='', blank=True)
date = models.DateField(default=datetime.datetime.today)
status = models.BooleanField(default=False)

def placeOrder(self):
self.save()
@staticmethod
def get_orders_by_customer(customer_id):
return Order.objects.filter(customer=customer_id).order_by('-date')

4. checkout.py:
from django.shortcuts import render, redirect

from django.contrib.auth.hashers import check_password


from store.models.customer import Customer
from django.views import View

from store.models.product import Products


from store.models.orders import Order

class CheckOut(View):
def post(self, request):
address = request.POST.get('address')
phone = request.POST.get('phone')
customer = request.session.get('customer')
cart = request.session.get('cart')
products = Products.get_products_by_id(list(cart.keys()))
print(address, phone, customer, cart, products)
for product in products:
print(cart.get(str(product.id)))
order = Order(customer=Customer(id=customer),
product=product,
price=product.price,
address=address,
phone=phone,
quantity=cart.get(str(product.id)))
order.save()
request.session['cart'] = {}

return redirect('cart')

5. orders.py:

from django.shortcuts import render, redirect


from django.contrib.auth.hashers import check_password
from store.models.customer import Customer
from django.views import View
from store.models.product import Products
from store.models.orders import Order
from store.middlewares.auth import auth_middleware

class OrderView(View):

def get(self, request):


customer = request.session.get('customer')
orders = Order.get_orders_by_customer(customer)
print(orders)
return render(request, 'orders.html', {'orders': orders})

Part 2: (Connecting the website With Artiicial Intelligence Using Machine Learning)
Building a recommendation system that can adjust product prices and offers based on user
engagement in the website .

Working Flow Diagram:

Figure 3(Model Architecture)


My Contribution:

Building a machine learning model that can predict the price and offers for a product based
on user involvement:

Creating backend api to receive request and return recommendation for this-

Step by Step Implementation:

Working Algorithm for Machine Learning Part:

1. Data collection and preprocessing:


Collect user interaction data and demographic information
Clean and transform data as needed

2. Problem definition and model selection:


Define problem as classification or regression task
Selecting machine learning algorithm

3. Model training and validation:


Split data into training and validation sets
Fit machine learning model to training data
Evaluate model performance on validation set

4. Model integration:
Create backend API to receive requests and return recommendations
Integrate machine learning model into website frontend

5. Model monitoring and improvement:


Continuously collect new data
Monitor model performance and adjust as needed
Update model architecture or retrain model entirely as needed
Working Flow For Backend API Part:

1. Choose a web framework: I had chosen Django framework that's compatible with
Python. Django is a full-featured web framework that includes many built-in
components

2. Defining endpoints: Once chosen a web framework, I define the endpoints for API.
An endpoint is a URL that can receive requests and return responses. For example,
I will define an endpoint /recommendations that accepts a user ID and returns a list
of recommended products.

3. Implement request handling: I will write code to handle requests to API endpoints.
This will typically involve parsing request parameters, passing them to the
machine learning model to generate recommendations, and returning the
recommendations in a suitable format, such as JSON or XML.

4. Deploy your API: Once I will implemented the API, I'll need to deploy it to a web
server or cloud platform so that it can be accessed by our website frontend.

Digital Signature (Student) Digital Signature (Guide)

You might also like