Untitled Document
Untitled Document
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 1D 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.
Admin Interface:
1. Admin Logs in
2. Admin inserts item
3. Admin removes item
4. Admin modifies item
Admin Interface:
ER-diagram for Admin
Step by Step Implementation:
Create Normal Project: Open the IDE and create a normal project by
selecting File->New Project.
1. Install Django: Next, we will install the Django module from the
terminal. We will use PyCharm integrated terminal to do this task.
One can also use cmd on windows to install the module by running
python -mpip install django command.
urls.py
This file contains all the URL patterns used by the website
python3
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.
Let’s See each model and fields required by each model.
Category.py
Python3
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
Customer.py
Python3
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)
@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
Products.py
Python
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()
Orders.py
Python
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')
Views:
In views, we create 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. Create an home.html, login.html, signup.html, cart.html,
checkout.html, orders.html in the templates. And map the views to the
store\urls.py folder.
Python
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'),
The below files show the views for each functionality of the site.
Home.py
Python3
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):
else:
cart[product] = 1
else:
cart = {}
cart[product] = 1
request.session['cart'] = cart
print('cart', request.session['cart'])
return redirect('homepage')
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
Login.py
Python3
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
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')
Signup.py
Python3
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)
Cart.py
Python
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')
Checkout.py
Python
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)
Orders.py
Python3
class OrderView(View):
Customer model:
It saves the basic data of the customers when they register
themselves.
Product model:
It saves the data of the product. The admin can add a new product
very easily using this model.
Feature model:
The admin can select the product and write any features about it.
And all the features of that product will be visible to the users when
they view a specific product.
Review model:
All the customers can write a review about a product which the
customers can read before buying it.
Order model:
It stores the order details about the customer, mainly the order id.
OrderItems model:
It stores the order id of the customer from the order model and the
products with their quantity.
Create superuser:
After creating the models, we need to go to the admin panel to
access the created models. Hence, we need a superuser who can
access the models from the admin panel. The superuser can make
any changes inside the models.
Creating superuser :For creating the superuser use the following command:
python manage.py createsuperuser
Urls.py file
Code Explanation:
Above mentioned are the app urls. Hence, create a file for the urls inside the
app. The last three urls are for the user authentication that is register, login
and logout. The other urls consist of the entire project.
<div class="row">
{% for product in products %}
<div class="col-lg-4 my-4">
<div class="card shadow align-items-center" style="width: 20rem; height: 25rem;">
<img src="/media/{{product.image}}" class="card-img-top" style="width: 170px;
height: 260px;" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.name}}</h5>
<hr>
{% if request.user.is_authenticated %}
<button data-product="{{product.id}}" data-action="add" class="btn add-btn
update-cart"
style="background-color: #8c5d4f; color: white;">Add To Cart</button>
<a href="/product_view/{{product.id}}/" class="btn
btn-outline-secondary">View</a>
{% else %}
<button class="btn" style="background-color: #8c5d4f; color: white;">Login to
add the item</button>
{% endif %}
<h4 style="display: inline-block; float: right;"> ₹{{product.price}}</h4>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
Views.py:
def index(request):
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
products = Product.objects.all()
return render(request, "index.html", {'products':products, 'cartItems':cartItems})
Code Explanation:
From the Product model, using a for loop all the products are displayed on the
home screen with the image, name and price of the products. Two buttons are
also created, one is for adding the item inside the cart and the other is to view
the product. If the customers are not logged in then they are not able to add
the item inside their cart. They can just see all the products. On the add to cart
button, login to add the item will be written.
<div class="row">
{% for product in products %}
<div class="col-lg-4 my-4">
<div class="card shadow" style="width: 20rem; height: 23rem;">
<img src="/media/{{product.image}}" class="card-img-top" alt="..."
height="230px">
<div class="card-body">
<h5 class="card-title">{{product.name}}</h5>
<hr>
{% if request.user.is_authenticated %}
<button data-product="{{product.id}}" data-action="add" class="btn add-btn
update-cart" style="background-color: #8c5d4f; color: white;">Add To Cart</button>
<a href="/product_view/{{product.id}}/" class="btn
btn-outline-success">View</a>
{% else %}
<button class="btn" style="background-color: #8c5d4f; color: white;">Login
to add the item</button>
{% endif %}
<h4 style="display: inline-block; float: right;">₹{{product.price}}</h4>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% else %}
<h1>You forgot to search</h1>
{% endif %}
Views.py:
def search(request):
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
if request.method == "POST":
search = request.POST['search']
products = Product.objects.filter(name__contains=search)
else:
Code Explanation:
The customers can directly search for the product that they want on the search
option given on the navigation bar. Whatever the customers write on the search bar
will be sent through a post request and then saved inside a variable.
search = request.POST['search']
products = Product.objects.filter(name__contains=search)
Afterwards, from the Product model the product name is filtered to the search value.
The result is then displayed in the same cards as on the home page.
Views.py:
if request.method=="POST":
content = request.POST['content']
review = Review(customer=customer, content=content, product=product)
review.save()
return redirect(f"/product_view/{product.id}")
return render(request, "product_view.html", {'product':product,
'cartItems':cartItems, 'feature':feature, 'reviews':reviews})
Code Explanation:
After clicking on the view button, the customers can view the specific
product with their key features and reviews. After reading the key features
and the reviews about the product, the customer can buy the product by
clicking on the add to cart button. The customer who has brought that
specific product can write their review about the product which the other
customer is able to read.
Views.py:
def cart(request):
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('Cart:', cart)
for i in cart:
try:
cartItems += cart[i]["quantity"]
product = Product.objects.get(id=i)
order["get_cart_total"] += total
order["get_cart_items"] += cart[i]["quantity"]
item = {
'product':{
'id':product.id,
'name':product.name,
'price':product.price,
'image':product.image,
},
'quantity':cart[i]["quantity"],
'get_total':total
items.append(item)
except:
pass
Code Explanation:
By clicking on the shopping cart icon on the navigation bar, customers can see
all the added items in the cart. The users can then increase or decrease the
quantity of the products according to their requirements.
</div>
<br>
</div>
</div>
Views.py:
def checkout(request):
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
total = order.get_cart_total
if request.method == "POST":
address = request.POST['address']
city = request.POST['city']
state = request.POST['state']
zipcode = request.POST['zipcode']
phone_number = request.POST['phone_number']
payment = request.POST['payment']
shipping_adress.save()
if total == order.get_cart_total:
order.complete = True
order.save()
alert = True
Code Explanation:
Then finally on the checkout page the customer can see their order
summary before placing the order which is very much important. At last,
the customers need to fill in the checkout details that includes the exact
address, city, zip code etc and also choose the mode of payment. Then the
customers can place their orders.
Views.py:
def change_password(request):
if not request.user.is_authenticated:
return redirect('/login')
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
if request.method == "POST":
current_password = request.POST['current_password']
new_password = request.POST['new_password']
try:
u = User.objects.get(id=request.user.id)
if u.check_password(current_password):
u.set_password(new_password)
u.save()
alert = True
else:
currpasswrong = True
except:
pass
Code Explanation:
All the customers can change their password by going to the change
password option. To check the current password (check_password)
method is used and (set_password) method is used to set the new
password as current password.
7. Contact Us (contact.html):
def contact(request):
if request.method=="POST":
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
contact.save()
alert = True
Code Explanation:
The customers can ask their queries or can contact us by filling a small form.
There are two different forms one for the logged in users and others who
haven’t registered themselves but want to contact us. If the user is a logged in
user then the user just have to write the message directly else the user needs to
first give his name, email and phone before contacting.
<div class="form-row">
</div>
</div>
</div>
<h4>Order Items:</h4>
<div class="my-4">
{% for i in order_items %}
<ol class="list-group">
</div>
<span class="badge bg-primary rounded-pill">Qty:
{{i.quantity}}</span>
</li>
</ol>
{% endfor %}
</div>
<div class="my-4">
{% for i in update_order %}
<ol class="list-group">
<div class="fw-bold">{{i.desc}}</div>
</div>
</li>
</ol>
{% endfor %}
</div>
</div>
</div>
Views.py:
def tracker(request):
if not request.user.is_authenticated:
return redirect('/login')
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']
if request.method == "POST":
order_id = request.POST['order_id']
order = Order.objects.filter(id=order_id).first()
order_items = OrderItem.objects.filter(order=order)
update_order = UpdateOrder.objects.filter(order_id=order_id)
print(update_order)
After placing the required order you will get an order id. That id can be further
used for tracking the order. In the track order menu you have to give your
order id for viewing the status of the order.
Summary:
We have successfully developed an Online Shopping System in Python
Django Framework. With this project, I think you will be understanding
and loving Django a lot more.