0% found this document useful (0 votes)
100 views46 pages

Untitled Document

This project deals with developing an e-commerce website using the Django framework. The website allows users to browse products, add items to a shopping cart, and checkout to place orders. It has functionality for customers to view products, manage their cart and checkout. It also has an admin interface to manage products, orders, and other site functionality. The project uses models like Category, Product, Customer, Order with a SQLite database. Views are created to handle requests and return HTML responses for different pages.

Uploaded by

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

Untitled Document

This project deals with developing an e-commerce website using the Django framework. The website allows users to browse products, add items to a shopping cart, and checkout to place orders. It has functionality for customers to view products, manage their cart and checkout. It also has an admin interface to manage products, orders, and other site functionality. The project uses models like Category, Product, Customer, Order with a SQLite database. Views are created to handle requests and return HTML responses for different pages.

Uploaded by

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

E-commerce Website using Django

This project deals with developing a Virtual website 'E-commerce Website'.


It provides the user with a list of the various products available for purchase
in the store. For the convenience of online shopping, a shopping cart is
provided to the user. After the selection of the goods, it is sent for the order
confirmation process.
The system is implemented using Python's web framework Django. To
develop an e-commerce website, it is necessary to study and understand
many technologies.

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.

Technologies used in the project:


Django framework and SQLite database which comes by defaut
with Django.
Required Skillset to Buitd the Project:
Knowledge of Python and basics of Django Framework.
Customer Interface:

1. Customer shops for a product


2. Customer changes quantity
3. The customer adds an item to the cart
4. Customer views cart
5. Customer checks out
6. Customer sends order
Use - Case Diagram For Customers

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.

2. Check Installed Django version: To check the installed Django


version, you can run the python -m django -version command as
shown below.

3. Create Django Project: When we execute django-admin


startprojectcommand, then it will create a Django project inside the
normal project which we already have created here. djanga-admin
startproject PrajectName.

4. Check Python3 version: python3-version

5. Run Default Django webserver:- Django internally provides a


default webserver where we can launch our applications. python
manage-py runservercommand in terminal. By default, the server
runs on port 8000. Access thewebserver at the highlighted URL
.
Open the project folder using a text editor. The directory structure should look like this :
Now add store app in E-commerce website in settings.py.

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)

# to save the data


def register(self):
self.save()

@staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True

return False
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'),

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


path('login', Login.as_view(), name='login'),
path('logout', logout, name='logout'),
path('cart', auth_middleware(Cart.as_view()), name='cart'),
path('check-out', CheckOut.as_view(), name='checkout'),
path('orders', auth_middleware(OrderView.as_view()), name='orders'),

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

Home.py

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):

def post(self, request):


product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if cart:
quantity = cart.get(product)
if quantity:
if remove:
if quantity <= 1:
cart.pop(product)
else:
cart[product] = quantity-1
else:
cart[product] = quantity+1

else:
cart[product] = 1
else:
cart = {}
cart[product] = 1

request.session['cart'] = cart
print('cart', request.session['cart'])
return redirect('homepage')

def get(self, request):


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

def store(request):
cart = request.session.get('cart')
if not cart:
request.session['cart'] = {}
products = None
categories = Category.get_all_categories()
categoryID = request.GET.get('category')
if categoryID:
products = Products.get_all_products_by_categoryid(categoryID)
else:
products = Products.get_all_products()

data = {}
data['products'] = products
data['categories'] = categories

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


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

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

def get(self, request):


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

def post(self, request):


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

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

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

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

Signup.py

Python3

from django.shortcuts import render, redirect


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

class Signup (View):


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

def post(self, request):


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

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

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

def validateCustomer(self, customer):


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

Cart.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')
Checkout.py

Python

from django.shortcuts import render, redirect

from django.contrib.auth.hashers import check_password


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

from store.models.product import Products


from store.models.orders import Order

class CheckOut(View):
def post(self, request):
address = request.POST.get('address')
phone = request.POST.get('phone')
customer = request.session.get('customer')
cart = request.session.get('cart')
products = Products.get_products_by_id(list(cart.keys()))
print(address, phone, customer, cart, products)

for product in products:


print(cart.get(str(product.id)))
order = Order(customer=Customer(id=customer),
product=product,
price=product.price,
address=address,
phone=phone,
quantity=cart.get(str(product.id)))
order.save()
request.session['cart'] = {}
return redirect('cart')

Orders.py

Python3

from django.shortcuts import render, redirect


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

class OrderView(View):

def get(self, request):


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

Explanation and use of models in this program.

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.

Checkout Details model:


It stores mainly the exact address where the order is to be
delivered.

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

Then, you can give the username, email and password.

Urls.py file

from django.urls import path


from . import views
urlpatterns = [
path("", views.index, name="index"),
path("cart/", views.cart, name="cart"),
path("checkout/", views.checkout, name="checkout"),
path("update_item/", views.updateItem, name="update_item"),
path("product_view/<int:myid>/", views.product_view, name="product_view"),
path("search/", views.search, name="search"),
path("contact/", views.contact, name="contact"),
path("loggedin_contact/", views.loggedin_contact, name="loggedin_contact"),

path("register/", views.register, name="register"),


path("change_password/", views.change_password, name="change_password"),
path("login/", views.Login, name="login"),
path("logout/", views.Logout, name="logout"),
]

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.

Home Page (index.html):

<div class="container mt-2 mb-3">

<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;">&nbsp;₹{{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.

2. Search Product functionality (search.html):

<div class="container mt-2 mb-3">

<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)

return render(request, "search.html", {'search':search, 'products':products,


'cartItems':cartItems})

else:

return render(request, "search.html")

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.

3. Product View Page (product_view.html):

<div class="container mt-4">


<div class="row">
<div class="col-md-4">
<div class="row">
<img src="/media/{{product.image}}" alt="" style="width: 300px; height: 400px;">
</div>
<br>
<div class="row">
<button data-product="{{product.id}}" data-action="add" class="btn add-btn
update-cart"
style="background-color: #8c5d4f; color: white; width: 15rem;">Add To
Cart</button> </div>
</div>
<div class="col-md-8">
<h3>{{product.name}}</h3>
<p style="font-size: 25px;"><b>₹ {{product.price}}</b></p>
<br>
<h5>Key Features:</h5>
<ul>
{% for i in feature %}
<li>{{i.feature}}</li>
{% endfor %}
</ul>
<br>
<h2>Add Reviews Here</h2>
<form method="POST" action="/product_view/{{product.id}}/"> {% csrf_token %}
<div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here"
id="floatingTextarea2"
style="height: 100px" id="content" name="content"></textarea>
<label for="floatingTextarea2">Leave a feedback about the
{{product.name}} here.</label>
<br>
<button type="submit" class="btn btn-primary">Add Review</button>
</div>
</form>
</div>
</div>
<div class="container mt-2">
<h2>All Reviews ({{reviews.count}})</h2>

{% for review in reviews %}


<div class="card">
<div class="card-header">
<span style="font-size: 22px;">{{review.customer}} </span> <span
style="font-size: 12px;">{{review.datetime | naturaltime}}</span>
</div>
<div class="card-body">
<h6 class="card-text">{{review.content}}</h6>
</div>
</div>
<br>
{% endfor %}
</div>
</div>
</div>

Views.py:

def product_view(request, myid):


product = Product.objects.filter(id=myid).first()
feature = Feature.objects.filter(product=product)
reviews = Review.objects.filter(product=product)
data = cartData(request)
items = data['items']
order = data['order']
cartItems = data['cartItems']

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.

4. Cart Page (cart.html):

<div class="container-fluid row">


<div class="col-lg-12">
<div class="box-element">
<a href="/" class="btn btn-outline-dark">&#x2190 Continue Shopping</a>
<br><br>
<table class="table">
<tr>
<th>
<h5>Items: <strong>{{order.get_cart_items}}</strong></h5>
</th>
<th>
<h5>Total: <strong>₹{{order.get_cart_total}}</strong></h5>
</th>
<th><a href="/checkout/" class="btn btn-success" style="float: right;
margin: 5px;">Checkout</a>
</th>
</tr>
</table>
</div>
<br>
<div class="box-element">
<div class="cart-row">
<div style="flex: 2;"><strong>Image</strong></div>
<div style="flex: 2;"><strong>Item</strong></div>
<div style="flex: 1;"><strong>Price</strong></div>
<div style="flex: 1;"><strong>Quantity</strong></div>
<div style="flex: 1;"><strong>Total</strong></div>
</div>
{% for item in items %}
<div class="cart-row">
<div style="flex: 2;"><img class="row-image" src="{{item.product.image.url}}"
alt=""></div>
<div style="flex: 2;">{{item.product.name}}</div>
<div style="flex: 1;">₹{{item.product.price}}</div>
<div style="flex: 1;">
<p class="quantity">{{item.quantity}}</p>
<div class="quantity">
<img data-product="{{item.product.id}}" data-action="add" src="{% static
'up-arrow.png' %}" class="chg-quantity update-cart" alt="">
<img data-product="{{item.product.id}}" data-action="remove" src="{%
static 'down-arrow.png' %}" class="chg-quantity update-cart" alt="">
</div>
</div>
<div style="flex: 1;">₹{{item.get_total}}</div>
</div>
{% endfor %}
</div>
</div>
</div>

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)

total = (product.price * cart[i]["quantity"])

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

return render(request, "cart.html", {'items':items, 'order':order,


'cartItems':cartItems})

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.

5. Checkout Page (checkout.html):

<div class="container-fluid row">


<div class="col-lg-12">
<div class="box-element">
<a class="btn btn-outline-dark" href="/cart/">← Back to Cart</a>
<hr>
<h3>Order Summary</h3>
<hr>
{% for item in items %}
<div class="cart-row">
<div style="flex:2"><img class="row-image"
src="{{item.product.image.url}}"></div>
<div style="flex:2">
<p>{{item.product.name}}</p>
</div>
<div style="flex:1">
<p>₹{{item.product.price}}</p>
</div>
<div style="flex:1">
<p>x{{item.quantity}}</p>
</div>
</div>
{% endfor %}
<h5>Items: {{order.get_cart_items}}</h5>
<h5>Total: ₹{{order.get_cart_total}}</h5>
</div>
</div>
<div class="col-lg-12">
<div class="box-element" id="form-wrapper">
<form method="POST"> {% csrf_token %}
<div id="shipping-info">
<hr>
<h4>Checkout Details:</h4>
<hr>
<div class="">
<input class="form-control" type="text" name="address"
placeholder="Address..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="city"
placeholder="City..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="state"
placeholder="State..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="zipcode"
placeholder="Zip code..">
</div>
<div class="form-field">
<input class="form-control" type="text" name="phone_number"
placeholder="Phone Number..">
</div>
</div>
<hr>
<input type="submit" value="Place Order" id="form-button" class="btn
btn-success">
</form>

</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 = CheckoutDetail.objects.create(address=address, city=city,


phone_number=phone_number, state=state, zipcode=zipcode, customer=customer,
total_amount=total, order=order, payment=payment)

shipping_adress.save()
if total == order.get_cart_total:

order.complete = True

order.save()

alert = True

return render(request, "checkout.html", {'alert':alert})

return render(request, "checkout.html", {'items':items, 'order':order,


'cartItems':cartItems})

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.

6. Change Password (change_password.html):


<form class="container mt-3" method="POST" name="change_password"
onsubmit="return checkPassword()">
{% csrf_token %}
<div class="row mt-4">
<div class="form-group col-md-6">
<label><i style="font-weight: bold;">Username</i></label>
<input type="text" class="form-control mt-2" name="username"
value="{{request.user}}" readonly>
</div>
<div class="form-group col-md-6">
<label><i style="font-weight: bold;">Current Password</i></label>
<input type="password" class="form-control mt-2" name="current_password"
placeholder="Current Password">
</div>
</div>

<div class="row mt-4">


<div class="form-group col-md-12">
<label><i style="font-weight: bold;">New Password</i></label>
<input type="password" class="form-control mt-2" name="new_password"
placeholder="Enter the new password">
</div>
</div>

<div class="row mt-4">


<div class="form-group col-md-12">
<label><i style="font-weight: bold;">Confirm Password</i></label>
<input type="password" class="form-control mt-2" name="confirm_password"
placeholder="Confirm the new password">
</div>
</div>
<input type="submit" class="btn mt-3" style="background-color: #8c5d4f; color:
white;">
</form>

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

return render(request, "change_password.html", {'alert':alert})

else:

currpasswrong = True

return render(request, "change_password.html",


{'currpasswrong':currpasswrong})

except:

pass

return render(request, "change_password.html", {'cartItems':cartItems})

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):

<div class="container py-2 mt-3">


<h2>Contact Us</h2>
<form method="post">{% csrf_token %}
<div class="form-group mt-2">
<label>Name</label>
<input type="text" class="form-control mt-2" id="name" name="name"
placeholder="Enter Your Name">
</div>
<div class="form-group mt-2">
<label>Email</label>
<input type="email" class="form-control mt-2" id="email" name="email"
placeholder="Enter Your Email">
</div>
<div class="form-group mt-2">
<label>Phone</label>
<input type="number" class="form-control mt-2" id="phone" name="phone"
placeholder="Enter Your Phone Number">
</div>
<div class="form-group">
<div class="form-group mt-2">
<label>How May We Help You ?</label>
<textarea class="form-control mt-2" id="desc" name="desc" rows="3"></textarea>
</div>
<button type="submit" style="background-color: #8c5d4f; color: white; width: 8rem;"
class="btn mt-4">Submit</button>
</form>
Views.py:

def contact(request):

if request.method=="POST":

name = request.POST['name']

email = request.POST['email']

phone = request.POST['phone']

desc = request.POST['desc']

contact = Contact(name=name, email=email, phone=phone, desc=desc)

contact.save()

alert = True

return render(request, 'contact.html', {'alert':alert})

return render(request, "contact.html")

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.

8. Track Order (tracker.html):


<div class="container py-5">

<div class="col mt-4">

<h2>Enter your Order Id to track your order.</h2>

<form method="post">{% csrf_token %}

<div class="form-row">

<div class="form-group col-md-6">

<input type="number" class="form-control mt-3"


name="order_id" placeholder="Order Id">

</div>

<button type="submit" class="btn btn-primary mt-4">Track


Order</button>

</div>

</div>

<div class="col my-4">

<h4>Order Items:</h4>

<div class="my-4">

{% for i in order_items %}

<ol class="list-group">

<li class="list-group-item d-flex justify-content-between ">

<div class="ms-2 me-auto">

<div class="fw-bold">{{forloop.counter}}. {{i.product}}</div>

</div>
<span class="badge bg-primary rounded-pill">Qty:
{{i.quantity}}</span>

</li>

</ol>

{% endfor %}

</div>

<h4>Your Order Details:</h4>

<div class="my-4">

{% for i in update_order %}

<ol class="list-group">

<li class="list-group-item d-flex justify-content-between ">

<div class="ms-2 me-auto">

<div class="fw-bold">{{i.desc}}</div>

</div>

<span class="badge bg-primary rounded-pill">Date:


{{i.date}}</span>

</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)

return render(request, "tracker.html", {'order_items':order_items,


'update_order':update_order})

return render(request, "tracker.html", {'cartItems':cartItems})


Code Explanation:

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.

You might also like