Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Major Project Report

ON

E-commerce website

SUBMITTED FOR THE PARTIAL FULFILMENT FOR THE AWARD OF THE DEGREE
MASTER IN COMPUTER APPLICATIONS
(Batch:2022-2024)

Submitted By:
Abhishek Mandal
Regd. No -2205201001

Under the esteemed guidance of


Prof. Rajib Kar
[Asst. Professor
Master In Computer Application

ESTD.– 1997
DEPARTMENT OF MASTER IN COMPUTER APPLICATIONS
SEEMANTA ENGINEERING COLLEGE, MAYURVIHAR, MAYURBHANJ,
ODISHA
Major Project Report
ON

E-commerce website
SUBMITTED FOR THE PARTIAL FULFILMENT FOR THE AWARD OF THE DEGREE
MASTER IN COMPUTER APPLICATIONS
(Batch:2022-2024)

Submitted By:
Abhishek Mandal
ROLL No -2322MCA10

Under the esteemed guidance of


Prof. Rajib Kar
[Asst. Professor]
Master In Computer Application

ESTD.– 1997
DEPARTMENT OF MASTER IN COMPUTER APPLICATIONS
SEEMANTA ENGINEERING COLLEGE, MAYURVIHAR, MAYURBHANJ,
ODISHA
EVALUATION OF PROJECT

E-commerce website

Internal Examiner External Examiner


CERTIFICATE

This is to certified that the project entitled " E-commerce website" submitted by
ABHISHEK MANDAL bearing Class Roll number : 2322MCA10, Examination
Regd number: 2205201001 of Seemanta Engineering College, Mayurbhanj,

Odisha is a bonafide work carried out by her under mysupervision and guidance to

the best ofmy knowledge the matter embodied in this report furnished are right for
this project and has not been submitted to any other university/institute for the

award of any degree or diploma.

Signature of the guide


DECLARATION

I Abhishek Mandal do here by declare that dissertation entitled


“ E-commerce website” is being submitted by me under the guidance of
Prof. Rajib Kar. I also declare that this dissertation report is a result of my
endeavor and that no part of the report has been submitted earlier for any
other degree in any university or published any time before on any form
by me.

Place :- Signature of the Candidate


Date :-
ACKNOWLEDGEMENT

At the outset, I would like to take the opportunity to thank Prof. Rajib Kar for
inspiring me to do this project. The opportunity provided by her helped me to
grow as a software developer as well as an individual.

I am also grateful to Prof. Rajib Kar, Head of the Department for assigning me
this interesting project and for her valuable suggestion and encouragement at
various stage of work. I am also grateful to all the faculty of MCAfor their valuable
suggestions and inputs during the course of the project work.

I express our gratitude to Prof. Anand Shankar Mohapatra, HOD of dept.


MCA, for his valuable suggestions and advices throughout the MCA course. I also
extend my thanks to other faculties for their co-operation during my course.

An assemblage of this nature could never have been attempted without the
reference and inspiration from the works of others whose details are mentioned
inreference section. I acknowledged my indebtedness to all of them.
Last but clearly not the least, my sincere thanks to all my friends who have
patiently extended all sorts of help and my utmost thank to The Almighty for
giving me strength to complete my report on time.

Abhishek Mandal
Roll no: 2322MCA10
Regd no: 2205201001
ABSTRACT

This project focuses on the development of an E-Commerce website


using the Django framework and Python programming language. The
objective of this endeavor is to create a robust and user-friendly platform
for online buying and selling, catering to the modern needs of digital
commerce. The project encompasses a comprehensive analysis of
requirements, design and implementation of key features, rigorous
testing, deployment, and considerations for maintenance and future
enhancements. By leveraging Django's powerful features such as its
ORM, authentication system, and built-in security measures, coupled
with Python's versatility and efficiency, the project aims to deliver a
scalable, secure, and efficient E-Commerce platform. Through this
project, we aim to contribute to the advancement of online retailing while
showcasing the capabilities of Django/Python in web development.
TABLE OF CONTENTS
1. Introduction
2. System Environment
2.1 Software Configuration
2.2 Hardware Configuration
3. Literature Review
3.1 Review of existing Existing E-Commerce platforms and their features
3.2 Analysis of similar projects developed using Django or similar frameworks
3.3 Discussion of Key Features and Functionalities Commonly Found in E-Commerce platforms
4. System Requirements Specification
4.1 Module Description
4.2 Process Flow Control
4.3 Functional requirements (user authentication)
4.4 Non-functional requirements (performance, security, scalability, etc.)
4.5 Use cases and user stories
5. Design:
5.1 System Architecture Overview:
5.2 UML Diagram:
5.3 E-R Diagram:
5.4 Data Flow Diagram
5.5 Description of Models, Views, and Templates in Django MVC Architecture
6. Implementation
6.1 Overview of the development process
6.2 Detailed explanation of key implementation aspects:
 User authentication
 creation and management
 Security measures implemented (e.g., protection against SQL injection, CSRF attacks)
6.1 Code snippets or excerpts highlighting important parts of the implementation
7. Testing
7.1 Description of testing methodologies employed (unit testing, integration testing, user acceptance
testing)
7.2 Test cases and results
8. Deployment
8.1 Deployment environment (mention hosting platform if any)
8.2 Deployment in Server process and steps taken
9. Visual Representations:
10. Summery
11. Conclusion
12. References
Introduction
The landscape of commerce has undergone a transformative shift in recent years,
propelled by the rapid proliferation of digital technologies and the internet. In this
digital era, the significance of E-Commerce cannot be overstated, as it offers
unprecedented opportunities for businesses to reach a global audience and for
consumers to access a diverse array of products and services from the comfort of
their homes. In light of these developments, the project at hand endeavors to create
a dynamic and robust E-Commerce website using the Django framework and Python
programming language.

1.1 Overview of the Project:

Our project centers on the development of an E-Commerce platform that seeks to


bridge the gap between sellers and buyers in the online marketplace. By harnessing
the power of Django, a high-level Python web framework known for its scalability and
versatility, we aim to construct a feature-rich website that facilitates seamless
transactions and fosters engaging user experiences.

1.2 Purpose and Objectives:

The primary purpose of this project is to empower businesses to establish an online


presence and leverage the vast potential of E-Commerce to expand their reach and
grow their sales. Concurrently, we aim to cater to the evolving needs of consumers
by providing them with a convenient and user-friendly platform for browsing,
purchasing, and managing their online shopping experiences.
System Environment

 Software Requirement

Operating System : Windows 10 / LinuxUser


Interface : HTML, CSS
Client-side Scripting : JavaScript
Programming Language : Python\Django
Web Technologies :
IDE/Workbench : Visual Studio
Database : SQlite 3.44.0
Server Deployment : Python Runserver
Framework : Django 3.0.5
Libraries and Dependencies : django-widget-tweaks==1.4.8

 Hardware Configuration:

CPU : Intel Core i3-2100 @ 3.70GHz


RAM : 4GB
Storage : 250GB HDD/SSD
Network : Gigabit Ethernet
Literature Review:

In the literature review section, we delve into existing research, studies, and
resources related to E-Commerce platforms, focusing on their features,
functionalities, and the technologies used for their development. This section
provides valuable insights into industry best practices, trends, and challenges, which
serve as a foundation for informing the design and development of our own E-
Commerce website.

3.1 Review of Existing E-Commerce platforms and their features:


Begin by surveying the landscape of existing E-Commerce platforms, ranging from
industry giants like Amazon and eBay to smaller boutique platforms catering to niche
markets.

Identify and analyze the key features and functionalities offered by these platforms,
such as product catalog management, user authentication, shopping cart
management, checkout process, order tracking, and customer support.

Discuss how these platforms differentiate themselves through unique features, such
as personalized recommendations, social sharing capabilities, subscription services,
and loyalty programs.

Highlight any emerging trends or innovations in E-Commerce platform development,


such as mobile commerce, voice commerce, augmented reality shopping
experiences, and blockchain-based solutions for supply chain transparency.
3.2 Analysis of Similar Projects Developed Using Django or Similar
Frameworks:
 Explore existing projects developed using Django or similar frameworks for
building E-Commerce websites.
 Evaluate the architecture, design choices, and implementation strategies
employed in these projects, focusing on their scalability, performance, and
security.
 Identify any challenges or limitations encountered in the development process
and how they were addressed.
 Discuss the availability of open-source libraries, plugins, and extensions that
facilitate the development of E-Commerce websites using Django or similar
frameworks.
 Draw insights from these projects to inform our own development approach and
identify opportunities for innovation and improvement.

Discussion of Key Features and Functionalities:

Common features found in BBMS developed using Django include:

User authentication and authorization mechanisms to control access to system


functionalities.

Donor registration forms with validation checks to ensure accurate donor


information.

Blood inventory management modules to track blood donations, expiration dates,


and available stock levels.

Blood request handling workflows for hospitals and healthcare facilities to place
orders for specific blood types.

Reporting and analytics tools to monitor blood utilization rates, identify trends, and
optimize inventory management strategies.

Overall, the literature review underscores the importance of BBMS in enhancing the
efficiency and effectiveness of blood bank operations. By leveraging Django's
capabilities, developers can create sophisticated BBMS solutions that address the
unique challenges faced by blood banks, ultimately improving patient outcomes and
saving lives
3.3 Discussion of Key Features and Functionalities Commonly Found
in E-Commerce platforms:

Key features and functionalities common to E-Commerce platforms include:

Product Management: Ability to add, edit, and delete products, manage categories
and attributes, and set pricing and inventory levels.

User Management: User registration, authentication, and profile management,


including features like wish lists, favorites, and order history.

Shopping Cart and Checkout: Seamless shopping cart management, with features
like product quantity adjustments, shipping options, and secure checkout processes.

Payment Processing: Integration with payment gateways to support various payment


methods and ensure secure transactions.

Order Management: Order tracking, status updates, and communication with


customers regarding order fulfillment and shipping.

Search and Navigation: Powerful search functionality and intuitive navigation menus
to help users find products quickly and easily.

Customer Support: Support channels such as live chat, email, and phone support,
along with self-service options like FAQs and help documentation.

Analytics and Reporting: Insights into sales performance, customer behavior, and
marketing effectiveness through analytics dashboards and reporting tools.

These features contribute to a seamless and engaging shopping experience for users
while providing businesses with the tools they need to manage their online
operations effectively.

In conclusion, the literature review provides valuable insights into the landscape of E-
Commerce platforms, the capabilities of Django and similar frameworks for E-
Commerce development, and the key features and functionalities that define
successful E-Commerce websites. This knowledge will inform the design and
development of our own E-Commerce platform, ensuring that it meets the needs of
both businesses and consumers in the competitive online marketplace.
Requirements Analysis:

Requirements analysis is a critical phase in the development process, where the


needs and expectations of stakeholders are identified and translated into specific
requirements that will guide the design and implementation of the project. This
section outlines the functional and non-functional requirements of the E-Commerce
website, as well as the use cases and user stories that capture the interactions
between users and the system.

4.1 Functional Requirements:


Functional requirements describe the specific behaviors and capabilities that the
system must exhibit to fulfill the needs of its users. These requirements define what
the system should do.

User Registration and Authentication:


Users should be able to create accounts, providing necessary information such as
username, email, and password.

Registered users should be able to log in securely to access their accounts and
perform actions such as browsing products, adding items to cart, and making
purchases.

Product Management:

 Admin users should be able to add, edit, and delete products, including details
such as name, description, price, and inventory.
 Products should be organized into categories and subcategories for easy
navigation and searchability.

Shopping Cart and Checkout:

 Users should be able to add items to their shopping cart, view cart contents,
and update quantities or remove items as needed.
 A streamlined checkout process should guide users through payment and
order confirmation, collecting necessary information such as shipping address
and payment method.
Order Management:

 Admin users should have access to an order management interface where they
can view and process orders, update order statuses, and communicate with
customers regarding order fulfillment and shipping.

Search and Navigation:

 Users should be able to search for products by keywords, categories, or


attributes, with search results displayed in a clear and organized manner.
 Navigation menus and filters should help users explore products and find what
they're looking for quickly and efficiently.

User Profile Management:

 Registered users should be able to manage their profiles, including updating


personal information, viewing order history, and managing preferences such as
communication preferences and saved addresses.
4.2 Non-functional Requirements:

Non-functional requirements specify the qualities or attributes that the system must
possess, such as performance, reliability, security, and usability. These requirements
describe how the system should behave.

Performance:

 The website should be responsive and load quickly, even under heavy traffic
loads.
 Database queries and transactions should be optimized for efficiency to
minimize response times.

Security:

 User data should be encrypted and stored securely to protect against


unauthorized access and data breaches.
 Payment processing should comply with industry standards for security and
encryption to ensure the confidentiality of financial information.

Scalability:

 The system should be designed to scale horizontally and vertically to


accommodate increasing numbers of users and transactions over time.
 Load balancing and caching mechanisms should be implemented to distribute
traffic evenly and improve performance.

Usability:

 The website should have a clean and intuitive user interface, with clear
navigation and visual cues to guide users through the shopping process.
 Accessibility features should be implemented to ensure that the website is
usable by people with disabilities.
4.3 Use Cases and User Stories:

Use cases and user stories provide detailed descriptions of how users interact with
the system and the specific actions they perform. These scenarios help to clarify the
requirements and define the user experience.

Use Case: User Registration

 User creates an account by providing required information.


 System validates user input and creates a new account.
 User receives a confirmation email with instructions for verifying their account.
Use Case: Adding Items to Cart

 User browses products and selects items to purchase.


 User adds selected items to their shopping cart.
 System updates cart contents and displays the updated total.
User Story: As a registered user, I want to be able to save multiple shipping
addresses so that I can easily select the appropriate address when placing orders.

User Story: As an admin user, I want to be able to view a list of pending orders and
process them efficiently by updating order statuses and communicating with
customers as needed.
Design:
The system architecture of the Blood Bank Management System (BBMS) outlines the
high-level structure and components of the software application. It defines how the
various modules and subsystems interact with each other to achieve the system's
objectives. Here's an overview of the system architecture:

Client-Side Interface: The client-side interface serves as the user-facing component


of the BBMS. It includes web-based interfaces for donors to register, healthcare
providers to request blood, and blood bank staff to manage inventory and
operations.

Server-Side Logic: The server-side logic consists of the application servers where the
business logic and processing occur. This includes functionalities such as donor
registration, blood inventory management, blood request handling, and reporting.

Database Management System (DBMS): The DBMS stores and manages the system's
data, including donor records, blood inventory, testing results, and transaction
history. It ensures data integrity, reliability, and accessibility for authorized users.

Integration with External Systems: The BBMS may integrate with external systems
such as laboratory information systems (LIS), electronic health record (EHR) systems,
and payment gateways. These integrations enable seamless data exchange and
interoperability with other healthcare IT systems.

Security Infrastructure: The system architecture includes security measures such as


encryption, authentication, and access control to protect sensitive data and ensure
compliance with privacy regulations. This may involve implementing role-based
access control (RBAC), encryption of data at rest and in transit, and regular security
audits.

Scalability and Performance Considerations: The architecture is designed to be


scalable and capable of handling varying levels of user traffic and data volume. This
may involve load balancing, caching, and database optimization techniques to
optimize performance and responsiveness.
Django MVC Architecture: Django follows the Model-View-Controller (MVC)
architectural pattern. Models represent the data structure, views handle user
interface logic, and templates generate HTML responses to be sent to the client.

Frontend and Backend Separation: The frontend is responsible for presenting the
user interface and handling user interactions, while the backend manages data
storage, business logic, and communication with external services.
Scalability Considerations: The architecture should be designed to scale horizontally
and vertically to accommodate growing user traffic and data volumes. This may
involve load balancing, caching, and distributed database architectures.

5.2. UML Diagram:


Unified Modeling Language (UML) diagrams provide a visual representation of the
system's structure, behavior, and interactions. In the context of the BBMS, the
following UML diagrams may be relevant:

Use Case Diagram: Illustrates the various use cases or functionalities of the system,
along with the actors (users or external systems) interacting with them. This helps in
identifying system requirements and defining user interactions.

Class Diagram: Represents the system's class structure, including classes, attributes,
methods, and relationships between them. This diagram helps in understanding the
data model and designing the system's object-oriented architecture.

Sequence Diagram: Shows the sequence of interactions between objects or


components in the system during a particular use case or scenario.
5.3 E-R Diagram:
The Entity-Relationship (E-R) diagram illustrates the entities (objects or
concepts) in the system, their attributes, and the relationships between
them. In the context of the BBMS, the E-R diagram may include entities
such as donors, blood units, healthcare providers, and transactions.
Relationships between entities, such as donation, request, and inventory
management, are defined to represent how they are related to each other.
5.4.Data Flow Diagram

The Data Flow Diagram (DFD) provides a graphical representation of the


flow of data within the system, showing how information moves between
processes, data stores, and external entities. In the BBMS, the DFD may
depict processes such as donor registration, blood request processing,
inventory management, and reporting. It also identifies data stores where
information is stored, such as the donor database, blood inventory
database, and transaction logs. Additionally, external entities such as
donors, healthcare providers, and external systems are depicted to show
their interactions with the system.
Coding & Implementation:

6.1 Overview of the Development Process using Django/Python:

The development process using Django/Python typically follows a structured


approach, encompassing planning, design, implementation, testing, and deployment
phases. Here's an overview of each stage:

Planning:

 Gather requirements from stakeholders to understand the project's objectives


and scope.
 Define user stories, use cases, and wireframes to capture functional and non-
functional requirements.
 Create a project plan outlining timelines, milestones, and resource allocation.

Design:

 Design the database schema using Django's ORM, defining models to represent
data entities and their relationships.
 Design the user interface (UI) using HTML, CSS, and JavaScript frameworks,
ensuring responsiveness and accessibility.
 Plan the architecture of the application, including views, URLs, and templates.

Implementation:

 Develop the backend logic using Django, including views, models, forms, and URL
routing.
 Implement frontend components using HTML templates and integrate them with
Django's templating engine.
 Configure settings such as database connections, static files, and middleware.
 Write tests to verify the functionality and integrity of the application.
Testing:

 Conduct unit tests, integration tests, and end-to-end tests to identify and fix bugs
and ensure the application meets requirements.
 Perform user acceptance testing (UAT) to gather feedback from stakeholders and
validate the usability and functionality of the application.

Deployment:

 Prepare the application for deployment by configuring production settings,


optimizing performance, and securing sensitive data.
 Deploy the application to a web server using platforms like Heroku, AWS, or
DigitalOcean.
 Monitor the application for performance, security, and scalability, and apply
updates and patches as needed.
6.2 Detailed Explanation of Key Implementation Aspects:

Backend Development with Django:


 Use Django's MTV (Model-Template-View) architecture to separate concerns and
maintain a clean codebase.
 Define models to represent data entities and relationships, leveraging Django's
ORM for database interaction.
 Implement views to handle HTTP requests, process data, and render templates.
 Configure URL patterns to map URLs to view functions, allowing for dynamic
routing and navigation.

Frontend Integration:

 Integrate frontend components with Django templates using template inheritance


and context data.
 Use Django's static file handling to manage CSS, JavaScript, and image assets.
 Leverage frontend frameworks like Bootstrap or Tailwind CSS for styling and
layout consistency.
 Implement AJAX functionality for dynamic content loading and asynchronous
form submissions.

Authentication and Authorization:

 Use Django's built-in authentication system to manage user registration, login,


and password reset functionality.
 Implement authorization mechanisms to restrict access to certain views or
resources based on user roles and permissions.
 Secure sensitive data and user sessions using techniques such as encryption, CSRF
protection, and session management.

Database Management:

 Choose a suitable database backend (e.g., PostgreSQL, MySQL, SQLite) based on


project requirements and scalability considerations.
 Define database models using Django's ORM, specifying fields, relationships, and
constraints.
 Generate and apply database migrations to manage schema changes and updates
over time.
 Optimize database queries and indexing for improved performance and
scalability.

Backend Development with Django:

 Use Django's MTV (Model-Template-View) architecture to separate concerns and


maintain a clean codebase.
 Define models to represent data entities and relationships, leveraging Django's
ORM for database interaction.
 Implement views to handle HTTP requests, process data, and render templates.
 Configure URL patterns to map URLs to view functions, allowing for dynamic
routing and navigation.

Frontend Integration:

 Integrate frontend components with Django templates using template inheritance


and context data.
 Use Django's static file handling to manage CSS, JavaScript, and image assets.
 Leverage frontend frameworks like Bootstrap or Tailwind CSS for styling and
layout consistency.
 Implement AJAX functionality for dynamic content loading and asynchronous
form submissions.

Authentication and Authorization:

 Use Django's built-in authentication system to manage user registration, login,


and password reset functionality.
 Implement authorization mechanisms to restrict access to certain views or
resources based on user roles and permissions.
 Secure sensitive data and user sessions using techniques such as encryption, CSRF
protection, and session management.

Database Management:

 Choose a suitable database backend (e.g., PostgreSQL, MySQL, SQLite) based on


project requirements and scalability considerations.
 Define database models using Django's ORM, specifying fields, relationships, and
constraints.
 Generate and apply database migrations to manage schema changes and updates
over time.
 Optimize database queries and indexing for improved performance and
scalability.
6.3 Code Snippets or Excerpts Highlighting Important Parts of the Implementation:

# Example of Model Definition in Django:


# models.py

from django.db import models

class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
inventory = models.PositiveIntegerField(default=0)

class Order(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
products = models.ManyToManyField(Product, through='OrderItem')
total_price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)

class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
unit_price = models.DecimalField(max_digits=10, decimal_places=2)

Example of View Implementation in Django:


# views.py

from django.shortcuts import render, redirect


from django.contrib.auth.decorators import login_required
from .models import Product

@login_required
def product_detail(request, product_id):
product = Product.objects.get(id=product_id)
return render(request, 'product_detail.html', {'product': product})

Example of Template Rendering in Django:


<!-- product_detail.html -->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ product.name }}</title>
</head>
<body>
<h1>{{ product.name }}</h1>
<p>{{ product.description }}</p>
<p>Price: ${{ product.price }}</p>
<!-- Additional HTML content for product details -->
</body>
</html>
User Authentication (views.py):

from django.shortcuts import render,redirect,reverse


from . import forms,models
from django.http import HttpResponseRedirect,HttpResponse
from django.core.mail import send_mail
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required,user_passes_test
from django.contrib import messages
from django.conf import settings

def home_view(request):
products=models.Product.objects.all()
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return
render(request,'ecom/index.html',{'products':products,'product_count_in_cart':product_count_in_car
t})

#for showing login button for admin(by sumit)


def adminclick_view(request):
if request.user.is_authenticated:
return HttpResponseRedirect('afterlogin')
return HttpResponseRedirect('adminlogin')

def customer_signup_view(request):
userForm=forms.CustomerUserForm()
customerForm=forms.CustomerForm()
mydict={'userForm':userForm,'customerForm':customerForm}
if request.method=='POST':
userForm=forms.CustomerUserForm(request.POST)
customerForm=forms.CustomerForm(request.POST,request.FILES)
if userForm.is_valid() and customerForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
customer=customerForm.save(commit=False)
customer.user=user
customer.save()
my_customer_group = Group.objects.get_or_create(name='CUSTOMER')
my_customer_group[0].user_set.add(user)
return HttpResponseRedirect('customerlogin')
return render(request,'ecom/customersignup.html',context=mydict)

#-----------for checking user iscustomer


def is_customer(user):
return user.groups.filter(name='CUSTOMER').exists()
#---------AFTER ENTERING CREDENTIALS WE CHECK WHETHER USERNAME AND PASSWORD IS OF ADMIN,CUSTOMER
def afterlogin_view(request):
if is_customer(request.user):
return redirect('customer-home')
else:
return redirect('admin-dashboard')

#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------
@login_required(login_url='adminlogin')
def admin_dashboard_view(request):
# for cards on dashboard
customercount=models.Customer.objects.all().count()
productcount=models.Product.objects.all().count()
ordercount=models.Orders.objects.all().count()

# for recent order tables


orders=models.Orders.objects.all()
ordered_products=[]
ordered_bys=[]
for order in orders:
ordered_product=models.Product.objects.all().filter(id=order.product.id)
ordered_by=models.Customer.objects.all().filter(id = order.customer.id)
ordered_products.append(ordered_product)
ordered_bys.append(ordered_by)

mydict={
'customercount':customercount,
'productcount':productcount,
'ordercount':ordercount,
'data':zip(ordered_products,ordered_bys,orders),
}
return render(request,'ecom/admin_dashboard.html',context=mydict)

# admin view customer table


@login_required(login_url='adminlogin')
def view_customer_view(request):
customers=models.Customer.objects.all()
return render(request,'ecom/view_customer.html',{'customers':customers})

# admin delete customer


@login_required(login_url='adminlogin')
def delete_customer_view(request,pk):
customer=models.Customer.objects.get(id=pk)
user=models.User.objects.get(id=customer.user_id)
user.delete()
customer.delete()
return redirect('view-customer')

@login_required(login_url='adminlogin')
def update_customer_view(request,pk):
customer=models.Customer.objects.get(id=pk)
user=models.User.objects.get(id=customer.user_id)
userForm=forms.CustomerUserForm(instance=user)
customerForm=forms.CustomerForm(request.FILES,instance=customer)
mydict={'userForm':userForm,'customerForm':customerForm}
if request.method=='POST':
userForm=forms.CustomerUserForm(request.POST,instance=user)
customerForm=forms.CustomerForm(request.POST,instance=customer)
if userForm.is_valid() and customerForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
customerForm.save()
return redirect('view-customer')
return render(request,'ecom/admin_update_customer.html',context=mydict)

# admin view the product


@login_required(login_url='adminlogin')
def admin_products_view(request):
products=models.Product.objects.all()
return render(request,'ecom/admin_products.html',{'products':products})

# admin add product by clicking on floating button


@login_required(login_url='adminlogin')
def admin_add_product_view(request):
productForm=forms.ProductForm()
if request.method=='POST':
productForm=forms.ProductForm(request.POST, request.FILES)
if productForm.is_valid():
productForm.save()
return HttpResponseRedirect('admin-products')
return render(request,'ecom/admin_add_products.html',{'productForm':productForm})

@login_required(login_url='adminlogin')
def delete_product_view(request,pk):
product=models.Product.objects.get(id=pk)
product.delete()
return redirect('admin-products')

@login_required(login_url='adminlogin')
def update_product_view(request,pk):
product=models.Product.objects.get(id=pk)
productForm=forms.ProductForm(instance=product)
if request.method=='POST':
productForm=forms.ProductForm(request.POST,request.FILES,instance=product)
if productForm.is_valid():
productForm.save()
return redirect('admin-products')
return render(request,'ecom/admin_update_product.html',{'productForm':productForm})

@login_required(login_url='adminlogin')
def admin_view_booking_view(request):
orders=models.Orders.objects.all()
ordered_products=[]
ordered_bys=[]
for order in orders:
ordered_product=models.Product.objects.all().filter(id=order.product.id)
ordered_by=models.Customer.objects.all().filter(id = order.customer.id)
ordered_products.append(ordered_product)
ordered_bys.append(ordered_by)
return
render(request,'ecom/admin_view_booking.html',{'data':zip(ordered_products,ordered_bys,orders)})

@login_required(login_url='adminlogin')
def delete_order_view(request,pk):
order=models.Orders.objects.get(id=pk)
order.delete()
return redirect('admin-view-booking')

# for changing status of order (pending,delivered...)


@login_required(login_url='adminlogin')
def update_order_view(request,pk):
order=models.Orders.objects.get(id=pk)
orderForm=forms.OrderForm(instance=order)
if request.method=='POST':
orderForm=forms.OrderForm(request.POST,instance=order)
if orderForm.is_valid():
orderForm.save()
return redirect('admin-view-booking')
return render(request,'ecom/update_order.html',{'orderForm':orderForm})

# admin view the feedback


@login_required(login_url='adminlogin')
def view_feedback_view(request):
feedbacks=models.Feedback.objects.all().order_by('-id')
return render(request,'ecom/view_feedback.html',{'feedbacks':feedbacks})

#---------------------------------------------------------------------------------
#------------------------ PUBLIC CUSTOMER RELATED VIEWS START ---------------------
#---------------------------------------------------------------------------------
def search_view(request):
# whatever user write in search box we get in query
query = request.GET['query']
products=models.Product.objects.all().filter(name__icontains=query)
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0

# word variable will be shown in html when user click on search button
word="Searched Result :"

if request.user.is_authenticated:
return
render(request,'ecom/customer_home.html',{'products':products,'word':word,'product_count_in_cart':
product_count_in_cart})
return
render(request,'ecom/index.html',{'products':products,'word':word,'product_count_in_cart':product_
count_in_cart})

# any one can add product to cart, no need of signin


def add_to_cart_view(request,pk):
products=models.Product.objects.all()

#for cart counter, fetching products ids added by customer from cookies
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=1

response = render(request,
'ecom/index.html',{'products':products,'product_count_in_cart':product_count_in_cart})

#adding product id to cookies


if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids=="":
product_ids=str(pk)
else:
product_ids=product_ids+"|"+str(pk)
response.set_cookie('product_ids', product_ids)
else:
response.set_cookie('product_ids', pk)

product=models.Product.objects.get(id=pk)
messages.info(request, product.name + ' added to cart successfully!')

return response

# for checkout of cart


def cart_view(request):
#for cart counter
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0

# fetching product details from db whose id is present in cookie


products=None
total=0
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids != "":
product_id_in_cart=product_ids.split('|')
products=models.Product.objects.all().filter(id__in = product_id_in_cart)

#for total price shown in cart


for p in products:
total=total+p.price
return
render(request,'ecom/cart.html',{'products':products,'total':total,'product_count_in_cart':product
_count_in_cart})

def remove_from_cart_view(request,pk):
#for counter in cart
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0

# removing product id from cookie


total=0
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
product_id_in_cart=product_ids.split('|')
product_id_in_cart=list(set(product_id_in_cart))
product_id_in_cart.remove(str(pk))
products=models.Product.objects.all().filter(id__in = product_id_in_cart)
#for total price shown in cart after removing product
for p in products:
total=total+p.price

# for update coookie value after removing product id in cart


value=""
for i in range(len(product_id_in_cart)):
if i==0:
value=value+product_id_in_cart[0]
else:
value=value+"|"+product_id_in_cart[i]
response = render(request,
'ecom/cart.html',{'products':products,'total':total,'product_count_in_cart':product_count_in_cart}
)
if value=="":
response.delete_cookie('product_ids')
response.set_cookie('product_ids',value)
return response

def send_feedback_view(request):
feedbackForm=forms.FeedbackForm()
if request.method == 'POST':
feedbackForm = forms.FeedbackForm(request.POST)
if feedbackForm.is_valid():
feedbackForm.save()
return render(request, 'ecom/feedback_sent.html')
return render(request, 'ecom/send_feedback.html', {'feedbackForm':feedbackForm})
#---------------------------------------------------------------------------------
#------------------------ CUSTOMER RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------
@login_required(login_url='customerlogin')
@user_passes_test(is_customer)
def customer_home_view(request):
products=models.Product.objects.all()
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0
return
render(request,'ecom/customer_home.html',{'products':products,'product_count_in_cart':product_coun
t_in_cart})

# shipment address before placing order


@login_required(login_url='customerlogin')
def customer_address_view(request):
# this is for checking whether product is present in cart or not
# if there is no product in cart we will not show address form
product_in_cart=False
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids != "":
product_in_cart=True
#for counter in cart
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0

addressForm = forms.AddressForm()
if request.method == 'POST':
addressForm = forms.AddressForm(request.POST)
if addressForm.is_valid():
# here we are taking address, email, mobile at time of order placement
# we are not taking it from customer account table because
# these thing can be changes
email = addressForm.cleaned_data['Email']
mobile=addressForm.cleaned_data['Mobile']
address = addressForm.cleaned_data['Address']
#for showing total price on payment page.....accessing id from cookies then fetching
price of product from db
total=0
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids != "":
product_id_in_cart=product_ids.split('|')
products=models.Product.objects.all().filter(id__in = product_id_in_cart)
for p in products:
total=total+p.price

response = render(request, 'ecom/payment.html',{'total':total})


response.set_cookie('email',email)
response.set_cookie('mobile',mobile)
response.set_cookie('address',address)
return response
return
render(request,'ecom/customer_address.html',{'addressForm':addressForm,'product_in_cart':product_i
n_cart,'product_count_in_cart':product_count_in_cart})

# here we are just directing to this view...actually we have to check whther payment is successful
or not
#then only this view should be accessed
@login_required(login_url='customerlogin')
def payment_success_view(request):
# Here we will place order | after successful payment
# we will fetch customer mobile, address, Email
# we will fetch product id from cookies then respective details from db
# then we will create order objects and store in db
# after that we will delete cookies because after order placed...cart should be empty
customer=models.Customer.objects.get(user_id=request.user.id)
products=None
email=None
mobile=None
address=None
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids != "":
product_id_in_cart=product_ids.split('|')
products=models.Product.objects.all().filter(id__in = product_id_in_cart)
# Here we get products list that will be ordered by one customer at a time

# these things can be change so accessing at the time of order...


if 'email' in request.COOKIES:
email=request.COOKIES['email']
if 'mobile' in request.COOKIES:
mobile=request.COOKIES['mobile']
if 'address' in request.COOKIES:
address=request.COOKIES['address']

# here we are placing number of orders as much there is a products


# suppose if we have 5 items in cart and we place order....so 5 rows will be created in orders
table
# there will be lot of redundant data in orders table...but its become more complicated if we
normalize it
for product in products:

models.Orders.objects.get_or_create(customer=customer,product=product,status='Pending',email=email
,mobile=mobile,address=address)

# after order placed cookies should be deleted


response = render(request,'ecom/payment_success.html')
response.delete_cookie('product_ids')
response.delete_cookie('email')
response.delete_cookie('mobile')
response.delete_cookie('address')
return response

@login_required(login_url='customerlogin')
@user_passes_test(is_customer)
def my_order_view(request):
customer=models.Customer.objects.get(user_id=request.user.id)
orders=models.Orders.objects.all().filter(customer_id = customer)
ordered_products=[]
for order in orders:
ordered_product=models.Product.objects.all().filter(id=order.product.id)
ordered_products.append(ordered_product)

return render(request,'ecom/my_order.html',{'data':zip(ordered_products,orders)})

#--------------for discharge patient bill (pdf) download and printing


import io
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse

def render_to_pdf(template_src, context_dict):


template = get_template(template_src)
html = template.render(context_dict)
result = io.BytesIO()
pdf = pisa.pisaDocument(io.BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return

@login_required(login_url='customerlogin')
@user_passes_test(is_customer)
def download_invoice_view(request,orderID,productID):
order=models.Orders.objects.get(id=orderID)
product=models.Product.objects.get(id=productID)
mydict={
'orderDate':order.order_date,
'customerName':request.user,
'customerEmail':order.email,
'customerMobile':order.mobile,
'shipmentAddress':order.address,
'orderStatus':order.status,

'productName':product.name,
'productImage':product.product_image,
'productPrice':product.price,
'productDescription':product.description,
}
return render_to_pdf('ecom/download_invoice.html',mydict)

@login_required(login_url='customerlogin')
@user_passes_test(is_customer)
def my_profile_view(request):
customer=models.Customer.objects.get(user_id=request.user.id)
return render(request,'ecom/my_profile.html',{'customer':customer})

@login_required(login_url='customerlogin')
@user_passes_test(is_customer)
def edit_profile_view(request):
customer=models.Customer.objects.get(user_id=request.user.id)
user=models.User.objects.get(id=customer.user_id)
userForm=forms.CustomerUserForm(instance=user)
customerForm=forms.CustomerForm(request.FILES,instance=customer)
mydict={'userForm':userForm,'customerForm':customerForm}
if request.method=='POST':
userForm=forms.CustomerUserForm(request.POST,instance=user)
customerForm=forms.CustomerForm(request.POST,instance=customer)
if userForm.is_valid() and customerForm.is_valid():
user=userForm.save()
user.set_password(user.password)
user.save()
customerForm.save()
return HttpResponseRedirect('my-profile')
return render(request,'ecom/edit_profile.html',context=mydict)

#---------------------------------------------------------------------------------
#------------------------ ABOUT US AND CONTACT US VIEWS START --------------------
#---------------------------------------------------------------------------------
def aboutus_view(request):
return render(request,'ecom/aboutus.html')

def contactus_view(request):
sub = forms.ContactusForm()
if request.method == 'POST':
sub = forms.ContactusForm(request.POST)
if sub.is_valid():
email = sub.cleaned_data['Email']
name=sub.cleaned_data['Name']
message = sub.cleaned_data['Message']
send_mail(str(name)+' || '+str(email),message, settings.EMAIL_HOST_USER,
settings.EMAIL_RECEIVING_USER, fail_silently = False)
return render(request, 'ecom/contactussuccess.html')
return render(request, 'ecom/contactus.html', {'form':sub}
models.py
"""
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
profile_pic=
models.ImageField(upload_to='profile_pic/CustomerProfilePic/',null=True,blank=True)
address = models.CharField(max_length=40)
mobile = models.CharField(max_length=20,null=False)
@property
def get_name(self):
return self.user.first_name+" "+self.user.last_name
@property
def get_id(self):
return self.user.id
def __str__(self):
return self.user.first_name

class Product(models.Model):
name=models.CharField(max_length=40)
product_image= models.ImageField(upload_to='product_image/',null=True,blank=True)
price = models.PositiveIntegerField()
description=models.CharField(max_length=40)
def __str__(self):
return self.name

class Orders(models.Model):
STATUS =(
('Pending','Pending'),
('Order Confirmed','Order Confirmed'),
('Out for Delivery','Out for Delivery'),
('Delivered','Delivered'),
)
customer=models.ForeignKey('Customer', on_delete=models.CASCADE,null=True)
product=models.ForeignKey('Product',on_delete=models.CASCADE,null=True)
email = models.CharField(max_length=50,null=True)
address = models.CharField(max_length=500,null=True)
mobile = models.CharField(max_length=20,null=True)
order_date= models.DateField(auto_now_add=True,null=True)
status=models.CharField(max_length=50,null=True,choices=STATUS)

class Feedback(models.Model):
name=models.CharField(max_length=40)
feedback=models.CharField(max_length=500)
date= models.DateField(auto_now_add=True,null=True)
def __str__(self):
return self.name
forms.py

from django.contrib import admin


from .models import Customer,Product,Orders,Feedback
# Register your models here.
class CustomerAdmin(admin.ModelAdmin):
pass
admin.site.register(Customer, CustomerAdmin)

class ProductAdmin(admin.ModelAdmin):
pass
admin.site.register(Product, ProductAdmin)
class OrderAdmin(admin.ModelAdmin):
pass
admin.site.register(Orders, OrderAdmin)
class FeedbackAdmin(admin.ModelAdmin):
pass
admin.site.register(Feedback, FeedbackAdmin)
# Register your models here.

Settings.py:
"""
Django settings for ecommerce project.

Generated by 'django-admin startproject' using Django 3.0.5.

For more information on this file, see


https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see


https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')

# Quick-start development settings - unsuitable for production


# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


SECRET_KEY = '#vw(03o=(9kbvg!&2d5i!2$_58x@_-3l4wujpow6(ym37jxnza'

# SECURITY WARNING: don't run with debug turned on in production!


DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ecom',
'widget_tweaks',

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

ROOT_URLCONF = 'ecommerce.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'ecommerce.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)


# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS=[STATIC_DIR,]

MEDIA_ROOT=os.path.join(BASE_DIR,'static')

LOGIN_REDIRECT_URL='/afterlogin'

#for contact us give your gmail id and password


EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'from@gmail.com' # this email will be used to send emails
EMAIL_HOST_PASSWORD = 'xyz' # host email password required
# now sign in with your host gmail account in your browser
# open following link and turn it ON
# https://myaccount.google.com/lesssecureapps
# otherwise you will get SMTPAuthenticationError at /contactus
# this process is required because google blocks apps authentication by default
EMAIL_RECEIVING_USER = ['to@gmail.com'] # email on which you will receive messages sent from
website

url.py:

"""
Developed By : sumit kumar
facebook : fb.com/sumit.luv
Youtube :youtube.com/lazycoders

"""
from django.contrib import admin
from django.urls import path
from ecom import views
from django.contrib.auth.views import LoginView,LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home_view,name=''),
path('afterlogin', views.afterlogin_view,name='afterlogin'),
path('logout', LogoutView.as_view(template_name='ecom/logout.html'),name='logout'),
path('aboutus', views.aboutus_view),
path('contactus', views.contactus_view,name='contactus'),
path('search', views.search_view,name='search'),
path('send-feedback', views.send_feedback_view,name='send-feedback'),
path('view-feedback', views.view_feedback_view,name='view-feedback'),

path('adminclick', views.adminclick_view),
path('adminlogin', LoginView.as_view(template_name='ecom/adminlogin.html'),name='adminlogin'),
path('admin-dashboard', views.admin_dashboard_view,name='admin-dashboard'),

path('view-customer', views.view_customer_view,name='view-customer'),
path('delete-customer/<int:pk>', views.delete_customer_view,name='delete-customer'),
path('update-customer/<int:pk>', views.update_customer_view,name='update-customer'),

path('admin-products', views.admin_products_view,name='admin-products'),
path('admin-add-product', views.admin_add_product_view,name='admin-add-product'),
path('delete-product/<int:pk>', views.delete_product_view,name='delete-product'),
path('update-product/<int:pk>', views.update_product_view,name='update-product'),

path('admin-view-booking', views.admin_view_booking_view,name='admin-view-booking'),
path('delete-order/<int:pk>', views.delete_order_view,name='delete-order'),
path('update-order/<int:pk>', views.update_order_view,name='update-order'),
path('customersignup', views.customer_signup_view),
path('customerlogin',
LoginView.as_view(template_name='ecom/customerlogin.html'),name='customerlogin'),
path('customer-home', views.customer_home_view,name='customer-home'),
path('my-order', views.my_order_view,name='my-order'),
path('my-profile', views.my_profile_view,name='my-profile'),
path('edit-profile', views.edit_profile_view,name='edit-profile'),
path('download-invoice/<int:orderID>/<int:productID>',
views.download_invoice_view,name='download-invoice'),

path('add-to-cart/<int:pk>', views.add_to_cart_view,name='add-to-cart'),
path('cart', views.cart_view,name='cart'),
path('remove-from-cart/<int:pk>', views.remove_from_cart_view,name='remove-from-cart'),
path('customer-address', views.customer_address_view,name='customer-address'),
path('payment-success', views.payment_success_view,name='payment-success'),

]
Aboutus.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>SS_coding || Sandip</title>

<title>sumit</title>
<style media="screen">
.footer{
position: fixed;
}
</style>
</head>

<body style="background-color: #B3E5FC;">


{%if request.user.is_authenticated%}
{% include "ecom/customer_navbar.html" %}
{%else%}
{% include "ecom/navbar.html" %}
{%endif%}
<br><br><br>
<h3 style="text-align:center;">“I don’t create companies for the sake of creating companies, but
to get things done.” </h3>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
{% include "ecom/footer.html" %}
</body>
<!--
developed By : sumit kumar
facebook : fb.com/sumit.luv
youtube : youtube.com/lazycoders
-->
</html>
Admin_add_product:
{% extends 'ecom/admin_base.html' %}
{% load widget_tweaks %}
{% block content %}

<head>
<style media="screen">
a:link {
text-decoration: none;
}

.note {
text-align: center;
height: 80px;
background: -webkit-linear-gradient(left, #0072ff, #8811c5);
color: #fff;
font-weight: bold;
line-height: 80px;
}

.form-content {
padding: 5%;
border: 1px solid #ced4da;
margin-bottom: 2%;
}

.form-control {
border-radius: 1.5rem;
}

.btnSubmit {
border: none;
border-radius: 1.5rem;
padding: 1%;
width: 20%;
cursor: pointer;
background: #0062cc;
color: #fff;
}

.menu {
top: 50px;
}
</style>

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"


id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<br><br><br><br><br><br>
<!------ update page for doctor by admin(sumit) ---------->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="container register-form">
<div class="form">
<div class="note">
<p>ADD PRODUCTS</p>
</div>
<div class="form-content">
<div class="row">
<div class="col-md-6">
<div class="form-group">
{% render_field productForm.name class="form-control" placeholder="Product Name" %}
</div>
<div class="form-group">
{% render_field productForm.description class="form-control"
placeholder="Description" %}
</div>

</div>
<div class="col-md-6">
<div class="form-group">
{% render_field productForm.price class="form-control" placeholder="Price" %}
</div>
<div class="form-group">
{% render_field productForm.product_image class="form-control"
placeholder="product_image" %}
</div>

</div>
</div>
<button type="submit" class="btnSubmit">ADD</button>
</div>
</div>
</div>
</form>
<!--
developed By : sandip kumar

-->
{% endblock content %}

Adminbase.html:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css">

<style type="text/css">
.bs-example {
margin: 0px;

}
.navbar-brand {
font-size: 20px;
font-family: sans-serif;

/*---------------------------------------
Social section
-----------------------------------------*/
footer {
padding: 0px 0px 0px 0px;
background-color: black;
margin: 0px;
}

#ftr {

padding: 20px;
}

.fa {

font-size: 23px;
width: 60px;
text-align: center;
text-decoration: none;
margin: 5px 2px;
border-radius: 50%;
}

.fa:hover {
opacity: 0.5;
text-decoration: none;
}

.fa-facebook {
background: #3B5998;
color: white;
margin-top: 30px;
}

.fa-whatsapp {
background: #25d366;
color: white;
}

.fa-twitter {
background: #55ACEE;
color: white;
}

.fa-instagram {
background: #125688;
color: white;
}
p {
text-align: center;

}
</style>
</head>

<body>

<div class="bs-example">
<nav class="navbar navbar-expand-md navbar-dark fixed-top" style="background:#337AB7;">
<a href="/" class="navbar-brand">Ecommerce</a>
<button type="button" class="navbar-toggler" data-toggle="collapse" data-
target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>

<div class="collapse navbar-collapse justify-content-between" id="navbarCollapse">


<div class="navbar-nav">
<a href="/view-customer" class="nav-item nav-link">Customer</a>
<a href="/admin-view-booking" class="nav-item nav-link">Booking</a>
<a href="/admin-products" class="nav-item nav-link">Products</a>
<a href="/view-feedback" class="nav-item nav-link">Feedback</a>
</div>

<div class="navbar-nav navbar-right">


<a href="/logout" class="nav-item nav-link">LOGOUT</a>
</div>

</div>
</nav>
</div>

<!-- content start-->


{% block content %}

{% endblock content %}
<!-- content end-->
<br><br><br><br><br><br><br><br>
<footer>
<p>
<a id="ftr" href="https://facebook.com/sumit.luv/" class="fa fa-facebook"></a>
<a id="ftr"
href="https://api.whatsapp.com/send?phone=919572181024&text=Hello%20Sumit.%0d%0aHow%20are%20you%20
%3f%0d%0aI%20came%20from%20your%20website.&source=&data=#" class="fa fa-whatsapp"></a>
<a id="ftr" href="https://instagram.com/sumit.luv" class="fa fa-instagram"></a>
<a id="ftr" href="https://twitter.com/sumitkumar1503" class="fa fa-twitter"></a>
</p>

<br>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12">
<div style="color:#ffffff;" class="wow fadeInUp footer-copyright">
<p>Made in India <br>
Copyright &copy; 2020 LazyCoder </p>
</div>
</div>
</div>
</div>
</footer>
<!--
developed By : sandip kumar
facebook : fb.com/sumit.luv
youtube : youtube.com/lazycoders
-->
</body>
</html>

customerlogin:
<!DOCTYPE html>
{% load widget_tweaks %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body {
margin: 0;
padding: 0;
font-family: sans-serif;
background: linear-gradient(to right, #b92b27, #1565c0)
}

.box {
width: 500px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
background: #191919;

text-align: center;
transition: 0.25s;
margin-top: 100px
}

.box input[type="text"],
.box input[type="password"] {
border: 0;
background: none;
display: block;
margin: 20px auto;
text-align: center;
border: 2px solid #3498db;
padding: 10px 10px;
width: 250px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s
}

.box h1 {
color: white;
text-transform: uppercase;
font-weight: 500
}

.box input[type="text"]:focus,
.box input[type="password"]:focus {
width: 300px;
border-color: #2ecc71
}

.box input[type="submit"] {
border: 0;
background: none;
display: block;
margin: 20px auto;
text-align: center;
border: 2px solid #2ecc71;
padding: 14px 40px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer
}

.box input[type="submit"]:hover {
background: #2ecc71
}

</style>
</head>
<body>
{% include "vehicle/navbar.html" %}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<form class="box" method="post">
{% csrf_token %}
<h1>Customer Login</h1>
<p class="text-muted"> Please enter your login and password!</p>

{% render_field form.username class="form-control" placeholder="Username" %}


{% render_field form.password class="form-control" placeholder="Password" %}

<input type="submit" name="" value="Login">

</form>
</div>
</div>
</div>
</div>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br>
{% include "vehicle/footer.html" %}
</body>
</html>

DonorlogIn:
<!DOCTYPE html>
{% load widget_tweaks %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body {
margin: 0;
padding: 0;
font-family: sans-serif;
background: linear-gradient(to right, #b92b27, #1565c0)
}

.box {
width: 500px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
background: #191919;

text-align: center;
transition: 0.25s;
margin-top: 100px
}

.box input[type="text"],
.box input[type="password"] {
border: 0;
background: none;
display: block;
margin: 20px auto;
text-align: center;
border: 2px solid #3498db;
padding: 10px 10px;
width: 250px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s
}

.box h1 {
color: white;
text-transform: uppercase;
font-weight: 500
}

.box input[type="text"]:focus,
.box input[type="password"]:focus {
width: 300px;
border-color: #2ecc71
}

.box input[type="submit"] {
border: 0;
background: none;
display: block;
margin: 20px auto;
text-align: center;
border: 2px solid #2ecc71;
padding: 14px 40px;
outline: none;
color: white;
border-radius: 24px;
transition: 0.25s;
cursor: pointer
}

.box input[type="submit"]:hover {
background: #2ecc71
}

</style>
</head>
<body>
{% include "vehicle/navbar.html" %}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<form class="box" method="post">
{% csrf_token %}
<h1>Mechanic Login</h1>
<p class="text-muted"> Please enter your login and password!</p>

{% render_field form.username class="form-control" placeholder="Username" %}


{% render_field form.password class="form-control" placeholder="Password" %}

<input type="submit" name="" value="Login">

</form>
</div>
</div>
</div>
</div>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br>
{% include "vehicle/footer.html" %}
</body>
</html>
Index.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">

<style>
.jumbotron{
margin-bottom: 0px;
}
</style>
<body>
{% include "quiz/navbar.html" %}
<br>
<section id="section-jumbotron" class="jumbotron jumbotron-fluid d-flex justify-content-center
align-items-center">
<div class="container text-center">
<h1 class="display-1 text-info">Let's Quiz</h1>
<p class="display-4 d-none d-sm-block">Test your skills and become a master.</p>
<p class="lead">We organize quizzes on various topics.</p>

<p class="lead">Sign up if you haven't already and get access to millions of quizzes on the
topic of your interest.</p>
<p><strong> Start Your Journey Here:</strong></p>
<a href="/student/studentsignup" class="btn btn-lg btn-info" style="padding-right: 35px;"><i
class="fa fa-user-plus" aria-hidden="true"></i> Sign Up</a>

<br><br><br>
</div>
</section>
{% include "quiz/footer.html" %}

</body>

</html>
Testing:
7.1. Description of Testing Methodologies Employed:
7.1. Description of Testing Methodologies Employed:

Testing methodologies ensure that the E-Commerce website functions as intended,


meets requirements, and is free from bugs and errors. Here are some testing
methodologies commonly employed:

Unit Testing:

Unit testing involves testing individual components or units of code in isolation to


verify that they perform as expected.

Python's built-in unittest or third-party libraries like pytest are commonly used for
writing and executing unit tests.

Unit tests cover functions, methods, and classes, checking for correctness of logic,
input validation, and edge cases.

Integration Testing:

Integration testing verifies that different components of the system work together
seamlessly.

In Django, integration tests may involve testing views with mock requests, testing
database interactions, and testing middleware functionality.

Integration tests ensure that the frontend and backend components communicate
correctly and that data flows smoothly through the system.

User Acceptance Testing (UAT):

UAT involves testing the E-Commerce website with real users or stakeholders to
validate its usability, functionality, and alignment with business requirements.

Test scenarios are created based on user stories and use cases, and users provide
feedback on their experience with the website.
UAT helps identify any usability issues, navigation problems, or missing features that
may impact user satisfaction.

Regression Testing:

Regression testing ensures that new code changes do not introduce unintended side
effects or break existing functionality.

Automated test suites are run on a regular basis to validate that previously tested
features still work as expected after code changes.

Regression tests cover critical paths and edge cases to catch regressions early in the
development process.

Security Testing:

Security testing involves identifying and mitigating vulnerabilities that could


compromise the security of the E-Commerce website.

Techniques such as penetration testing, vulnerability scanning, and code review are
used to assess the website's security posture.

Security testing helps protect sensitive user data, prevent unauthorized access, and
ensure compliance with security standards and regulations.

7.2 Test Cases and Results:


Test Case: User Registration

Description: Verify that users can register for an account with valid information.
Steps: Navigate to the registration page, enter valid user details, submit the
registration form.

Expected Result: User is registered successfully, and a confirmation email is sent.

Result: Test passed.


Test Case: Adding Product to Cart

Description: Verify that users can add products to their shopping cart.
Steps: Navigate to the product detail page, click on the "Add to Cart" button.

Expected Result: Product is added to the cart, and cart total is updated.
Result: Test passed.

Test Case: Checkout Process

Description: Verify that users can complete the checkout process successfully.

Steps: Navigate to the shopping cart, proceed to checkout, enter shipping and
payment information, confirm order.

Expected Result: Order is placed successfully, and user receives an order


confirmation email.

Result: Test passed.

Test Case: Login Authentication

Description: Verify that only authenticated users can access protected pages.

Steps: Attempt to access a protected page without logging in.

Expected Result: User is redirected to the login page.

Result: Test passed.


Deployment:
8.1 Deployment Environment:

The deployment environment refers to the infrastructure where the online quiz
application is deployed and made accessible to users. Here's an overview:

 Hosting Platform: Choose a hosting platform to deploy the application.


Popular options include cloud providers such as AWS (Amazon Web Services),

Google Cloud Platform, Microsoft Azure, or dedicated hosting providers like


Heroku, DigitalOcean, or Linode. The choice depends on factors such as
scalability, performance, pricing, and developer familiarity.

 Server Configuration: Set up the server environment to host the Django


application. This may involve configuring web servers (e.g., Apache, Nginx),
application servers (e.g., Gunicorn, uWSGI), database servers (e.g., PostgreSQL,
MySQL), and other required services (e.g., Redis for caching).

Domain Name and SSL Certificate: Obtain a domain name for the application and
configure DNS settings to point to the server's IP address. Install an SSL certificate to

enable HTTPS encryption and ensure secure communication between clients and the
server.

8.2 Deployment Server Process and Steps Taken:

The deployment process involves transferring the application from the development
environment to the production environment. Here's a step-by-step guide to the
deployment process:
To deploy a Django project using the `runserver` command for development
purposes, you can follow these steps:
 Ensure Dependencies are Installed:
Make sure you have Python and Django installed on your system. You can install
Django using pip:

pip install Django

 2. Install all Packages(all packages in requrements.txt file):


pip –r install requirements.txt

 2. Navigate to Project Directory:


Open a terminal or command prompt and navigate to the root directory of your
Django project.

 3. Run Migrations:
Before starting the development server, it's a good practice to apply any database
migrations:

```
python manage.py makemigrations

python manage.py migrate

```

 Start Development Server:


Once migrations are applied, you can start the development server using the
`runserver` command:

```
python manage.py runserver

```
This command will start the server, and you'll see output similar to:
```
Performing system checks...

System check identified no issues (0 silenced).

April 21, 2024 - 15:28:00

Django version 3.0.7, using settings 'myproject.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

```

 Access Your Project:


Open a web browser and navigate to `http://127.0.0.1:8000/` (or
`http://localhost:8000/`). You should see your Django project's home page or the
default Django welcome page if you haven't set up your project yet.

 Development Workflow:
Make any necessary changes to your project's code. The development server
automatically detects changes and reloads the server, allowing you to see your
updates in real-time.

 Access Django Admin:


To access the Django admin interface, navigate to `http://127.0.0.1:8000/admin/`.
You'll need to create a superuser account using the `createsuperuser` command if
you haven't already:
```
python manage.py createsuperuser

```
Follow the prompts to create a superuser account, and then log in to the admin
interface to manage your project's data.

 Stopping the Server:


To stop the development server, press `CTRL + C` in the terminal where the server
is running. Confirm by typing `Y` and pressing `Enter`.

 Deployment Considerations:
Remember that the `runserver` command is intended for development use only
and is not suitable for production deployment. For production deployment, you'll
need to use a production-grade server such as Gunicorn or uWSGI and configure it to
serve your Django application.

By following these steps, you can deploy your Django project using the `runserver`
command for development purposes and access it in a web browser on your local
machine.
Visual Representations:

 Index Module
 Homepage

 Admin LogIn
 Admin Module
 Customer Module

 Customer

 Customer LogIn
Project Summary:

The development of the E-Commerce website using Django/Python involved a


comprehensive process encompassing planning, design, implementation, testing, and
deployment. The project aimed to create a robust and user-friendly platform for online
retail, leveraging the powerful features and functionalities offered by the Django
framework.

The project began with requirements gathering, where stakeholder needs and
expectations were identified and translated into design specifications. The
development team then proceeded to implement the design specifications, focusing on
building both the frontend and backend components of the website.

Key aspects of the implementation included:

 Backend development using Django, which involved defining models, views, and
URL routing to handle user requests, process data, and generate responses.
 Frontend integration, where HTML templates were created and integrated with
Django's templating engine to render dynamic user interfaces.
 Authentication and authorization mechanisms were implemented to secure user
data and restrict access to certain views or resources.
 Database management, including designing the database schema, defining models,
and optimizing database queries for performance.
 Testing methodologies employed included unit testing, integration testing, user
acceptance testing (UAT), regression testing, and security testing. Test cases were
designed to validate the functionality, usability, and security of the website,
ensuring a high-quality end product.

Overall, the E-Commerce website provides a seamless and engaging shopping


experience for users, with features such as user registration, product management,
shopping cart functionality, checkout process, and user authentication. The project
adhered to best practices and standards in web development, resulting in a scalable,
secure, and maintainable platform for online retail.

With the successful completion of the project, the E-Commerce website is ready for
deployment to production environments, where it will serve as a valuable asset for
businesses looking to establish or expand their online presence.
Conclusion:

In conclusion, the development of the E-Commerce website using Django/Python has


been a significant undertaking that has resulted in the creation of a robust and
feature-rich platform for online retail. Throughout the project lifecycle, careful
planning, meticulous design, diligent implementation, thorough testing, and
meticulous attention to detail have been paramount in achieving success.

The project has successfully addressed the diverse needs and requirements of
stakeholders, providing a user-friendly interface for customers to browse products,
make purchases, and manage their accounts, while also offering powerful backend
functionality for administrators to manage products, orders, and user accounts
efficiently.

Key highlights of the project include the utilization of Django's powerful features and
conventions to streamline development, the implementation of security measures to
protect user data and ensure safe transactions, and the incorporation of testing
methodologies to verify the functionality, usability, and security of the website.

Looking ahead, the E-Commerce website stands poised to make a significant impact
in the online retail space, offering businesses a powerful tool to reach customers,
drive sales, and grow their brand presence. With ongoing support and maintenance,
the website will continue to evolve and adapt to meet the changing needs and
expectations of users and stakeholders.

Overall, the successful completion of the project underscores the effectiveness of


Django/Python as a framework for building complex web applications and
demonstrates the value of a systematic approach to development. The E-Commerce
website represents a culmination of hard work, collaboration, and dedication, and it
is poised to make a meaningful contribution to the world of online
commerce.Looking ahead, we remain committed to the ongoing maintenance,
support, and enhancement of the BBMS. We will continue to monitor feedback from
users, address any issues that arise, and implement updates and new features to
ensure that the system remains relevant, reliable, and effective in supporting blood
banking operations.

In conclusion, the Blood Bank Management System represents a significant milestone


in our mission to leverage technology for the betterment of healthcare. We are
proud of the accomplishments achieved thus far and look forward to the continued
success and impact of the BBMS in improving blood banking processes and ultimately
contributing to better patient outcomes.
References:
For an Example
[1] Django Documentation: https://docs.djangoproject.com/en/stable/
[2] Django Girls Tutorial: https://tutorial.djangogirls.org/en/
[3] Mozilla Developer Network (MDN) Web Docs - HTML:
https://developer.mozilla.org/en-US/docs/Web/HTML
[4] CSS-Tricks - CSS Reference: https://css-tricks.com/almanac/
[5] JavaScript MDN Web Docs: https://developer.mozilla.org/en-
US/docs/Web/JavaScript

[6] Django Official Github Repository: https://github.com/django/django


[7] Python Package Index (PyPI): https://pypi.org/
[8] W3Schools - Django Tutorial: https://www.w3schools.com/django/
THANK YOU

You might also like