How to Build an E-commerce Website Using Django, HTML, CSS and Javascript

Introduction

In this tutorial, we shall be looking at how we can build an e-commerce platform where users can buy goods, pay, and order, list goods. It is suitable for businesses, especially during this pandemic to embrace this so that their customers can easily buy products online without having any issues. Ecommerce in recent years has been on the rise, which made a lot of people look into it and start online shops. The e-commerce platform is an online platform where you can buy anything listed, pay for it, and get it shipped to where you said when filling the shipping address.

Intended Audience: Who the article is for

This article is mainly for Python/Django developers who want to build a project to showcase their skills. The article can also help people who want to build an e-commerce site and start selling their products. This e-commerce project will consist of different Django concepts, which enable developers to develop projects basing on this.

Case Study: What is the Article going to Cover

It will cover how to build an e-commerce platform where users can sign up, log in, log out, view products, view orders, update profile/shipping address, buy, make payments and have them shipped to the address they gave. The platform has been built using Django.

Requirements

  1. Knowledge of Python and Django
  2. Knowledge of JavaScript, HTML, and CSS
  3. Use of pip
  4. How to Use the terminal.
  5. Using an IDE.
  6. Stripe and GitHub account.

Getting Started on How To Build The Sumiasell Ecommerce Platform

Creating The Project

  1. Let’s create our project called ‘’sumiasell” by typing the following command on the terminal: django-admin startproject sumiasell.
  2. Now let’s create our environment by typing the following command on the terminal: python –m venv venv
  3. Now, let’s activate the virtual environment:
  4. On windows type:venv\Scripts\activate to activate the virtual environment.
  5. On Mac/Linux:sourcevenv/bin/activate to activate the virtual environment
  6. After activating the virtual environment, lets now install the dependencies of the project using pip by typing the following on the terminal:

  “pip install pillow”: python package to be used in managing images

 “pip install django”: python package to be used in building the web app

pip install Django-countries”: python package to be used in enabling us to list all countries in the shipping address.

pip install django all-auth”: python package to be used in setting up the login details to username, not an email address

pip install stripe”: python package to be used in managing the stripe payments

pip install django-crispy-forms”: to be used rendering bootstrap styles in HTML templates

7. Now let’s create our Django apps by typing the following command on the terminal:

python manage.py startapp sumiacart-create sumiacart app

python manage.py startapp sumiacheckout-create sumiacheckout app

python manage.py startapp sumiaproducts-create sumiaproducts app

8. We will be using the SQLite database, to create it, type the following command on the terminal: python manage.py migrations.

9.Now let’s apply our database changes by typing the following on the terminal: python manage.py migrate

10.Now let’s start our server by typing the following command on the terminal: python manage.py runserver

11.If the server runs well you will get a webpage http://127.0.0.1:8000 showing it’s a success. You can type Ctrl+ C to stop the server so that you can work on other parts of the app.

Configuring Our Project Settings

1.Now let’s locate our project folder named “sumiasell

2.Head over to the settings.py file and locate the variable INSTALLED_APPS and add the following apps below.

3.We also have to add the Django crispy form as an app which will be used for making the HTML pages look better and used for rendering any HTML element. Add the following code to the settings.py file:

4.Add all-auth as an app on the installed apps in the settings.py

5.Add the django-countries as an app to the settings.py to handle the database of the countries

6.We will also need to tell crispy forms that we will be using Bootstrap 4 in rendering our HTML templates by adding the following code at the bottom of the settings.py

7.We shall also have media_url and media_root.Media_url is the URL that will serve the media files which are images, while media_root is the path to the root directory where the files will be stored. All the uploaded images of the products will be stored in the media directory.

8.We are also going to set up Gmail as our Django email client. This will be used for resetting the password. To learn more about setting Gmail as a Django client check this post here. Add the following code to the settings.py

9.Head over to stripe.com and copy the API keys that we will be using to interact with the stripe API during payments. Remember to turn on the test data during the copying of secret and publishable key

Here is the full code of settings.py

Other Settings of the Sumiasell Project.

sumiasell/urls.py.

It helps in routing the urls to the views. We shall import four modules:

from django.contrib import admin-It is used to import the admin module in the application.

from django.urls import path, include– this module is used to return an element for inclusion in the url patterns.

from django.conf import settings-this module is used to import the first module named settings.py in the system path

from django.conf.urls.static import static-this module helps us in managing the static files and on how you can serve them.

Then we will import OrdersListView and Refund view from sumiacart app views and ShippingAddressUpdateView from sumiacheckout app view.

 It will have the urls patterns for: admin, products, cart, checkout, accounts, profile, orders and refunds.

Here is the code of urls.py

sumiasell/asgi.py

Contains the ASGI configuration of the app.

sumiasell/wsgi.py

It contains the WSGI configuration of the app.

Main Functionalities of Apps

sumiacart

sumiacart/admin.py

In admin.py, we shall be registering the models that we will be using in the admin panel. We shall register order items, order, and refund.

Here is the code

sumiacart/apps.py

It consists of the sumiacart app configuration.

sumiacart/models.py

This will represent our app database.

We need to import the following modules:

 from django.db import models – It is used to convert a python class to a database table

from django.conf import settings-It is used to import the settings of the app

from django import forms –It is used to import the form functionalities of the app.

Our models will consist of four classes which will consist of different fields: OrderItem class, Order class, Refund class, RefundForm class.

i)OrderItem class

This model will be when a buyer orders an item. It will consist of the user column representing the user’s details, item column representing the products listed on the site, quantity column shows the number of goods added to the cart and the created_date field representing the day the order was created by the customer.

The function __str__ will be used to return the item and quantity when displaying them on the admin site, while the get_total function will be used to get the total cost of the order placed by a customer.

ii)Order class

This database model will represent the customer selection of an item.

It will consist of the following fields: order id column to represent the order id of an item, user column to represent the details of the user, items column to represent the products ordered, created_date column to represent when the customer placed the order, shipping_address column to represent the shipping address of the customer, payment column to represent the payment being done on the ordered items, promo_code_applied column to represent the promo code being applied,promo_code_discount column to represent the rate or the amount of promo code applied on the total cost,refund_requested column that represents the customer if he asked for a refund and refund_granted column if the refund requested was granted to the user.

The __str__ function will be used for returning the object representation of the database object created in the OrderItem table. The class has functions also:get_total_function that shows the total amount the user has to pay for the products, get_all_items function to show all the products added to the cart, get_total quantity to show the total number of items bought by the customer.

iii)Refund class

This model will be for the refund process. The class will consist of the following columns: the reason column will represent the reason the customer gives when typing for a refund, the order column will represent the order id of the item the customer is asking a refund for, the granted column will represent whether the refund was given or not.

The __str__ function will be used for returning the string representation of object tables created in the Refund table.

 iv)RefundForm class

It will represent the form where the user fills the refund request. It will have the order_id column representing the order of an item that refund is being asked for.

Here is the code of sumiacart/models.py

sumiacart/urls.py

This will help the user navigate the app. We will use four URLs:

Show-cart:- The URL to enable the user to see the details of the cart

Add-to-cart:- The URL responsible for adding products to the cart

Increase-product-in-cart-URL responsible for the user to increase the number of quantities in the cart.

Remove-from-cart-the URL that will enable the user to remove products from the cart.

Decrease-product-in-cart-URL that will enable the user to reduce the quantity.

Here is the sumiacart/urls.py code:

sumiacart/views.py

These are responsible for taking the web requests and returning a web response. We shall import order, OrderItem, Refund from project models, and import product from sumiaproducts app models.

We shall use the following modules:

from django.contrib import messages-This is used to send up messages from the app views to the HTML pages.

from django.shortcuts import redirect,get_object_or_404-This is the module used for rendering the HTML pages to the customers.

from django.urls import reverse lazy-This module is used to resolve a URL name

from django.contrib.auth.decorators import login_required-This module uses decorators which forces the user to log in to access the views of the app.

from django.contrib.auth.mixins import LoginRequiredMixin-This module is used to limit the user in accessing associated views unless he logs in.

from django.contrib.messages.views import SuccessMessageMixin-This module is for sending success messages from view to the html page.

from django. views. generic import Listview, DetailView, View-this model is used for displaying a list of records from a specific database table, showing all the details of a specific entry of a database.

from.django.views.generic.edit import Formview-this modules help the views to display a form

from django.http import jsonResponse-this modules help in creating a JSON-encoded response from a HttpRespose subclass.

It will consist of different classes:

RefundView class-This will be used to display for the customers who want a refund for their orders. For one to request a refund, he has to log in. It will be used for rendering the refund HTML template. If the customer’s order id is valid, the customer receives a message that the request has been successful. The form valid function checks if the customer has provided a valid order-id; If not right it tells the customer that order_id is invalid.

OrdersListView class-This will be used to display all the orders replaced by the customer. It also requires a login for the user to access the page.

CartDetailView class-It is used to display the details of the cart from the product, no, price, amount, discount, etc. It will be used to render the cart HTML template.

AddToCartAjax class-this enables the users to add products to the cart. A user cannot add products to the cart without an account so he has to log in.

 This class will have several functions: increase_product_in_cart function that enables the user to add products to cart and requires a login,decrease_product_in_cart function that enables users to reduce the quantity may be from 3 to 1 product, remove_from_cart function allows users to remove the products from the cart completely. You will get a congratulatory message telling you your product has successfully been added to the cart if you manage to add to the cart successfully.

Here is the code of sumiacart/views.py

sumiacart/templetags

This will be used to register the cart icon.

Here is the code of temple tags.

Sumiacheckout

Let’s now look at the functionalities of the sumiacheckout app.

sumiacheckout/admin.py

This is where we register our models. We shall register ShippingAddress, Promotioncode, Payment, which is imported from models.

Here is the code:

sumiacheckout/apps.py

Contains the app configuration of sumiacheckout.

sumiacheckout/models.py

It will consist of different classes. We shall import different modules in the database table:

from django_countries.field import CountryField-This will help in importing the names of countries from the countries database.

from django.db import models-This module is used to convert a python class to a database table

from django import forms-this modules help in handling and creating forms easier.

from django.URLs import reverse lazy-This module is used to resolve a url name

from Django. core. validators import MaxValueValidator, MinValueValidator- this plays a key role in re-using the validation logic used between different types of fields in the database.

from django.conf import settings- this module is used to import the first module named settings.py in the system path

It will consist of different classes:

ShippingAddress class-It will consist of first name column which stores the first name in the database, last name column which stores the last name of the customer in the database, the street column which stores the name of the street in the database, street number column which stores the street number in the database, zip code column for storing the zip code of the street, city column to store the city which customer comes from, country column to store the country where the customer resides, phone number column to store the phone number of the customer and current address column to store where the customer is currently located

The __str__ function will return the string representation of the username, street, street number, and city in the ShippingAddress table

The get_absolute_url function will enable the user to be redirected to their profile once they fill in their shipping address.

ShippingAddressForm class-Enables the database save the form after being filed by the customer. This is facilitated by the save_address form.

Payment class-handles the payment of stripe. It consists of a user column to keep the details of the user in the database, stripe_id column to keep the stripe id of the customer, amount column to store the total amount the customer is paying for the products ordered, issued_data column to store the data that has been issued by the customer.

The __str__ function will return the string representation of username and amount in the Payment database.

PromotionCode class-Saves the promotion code provided, the promotion percentage varies from 0.1-1.0 of the total cost. It has a code column that saves the promotion code into the database, the percentage_discount column which saves the percentage that will be subtracted from the total cost.

The __str__function returns the string representation of the promotion code in the PromotionCode database.

PromotionCodeForm class-saves the form for the promotion code.

Sumiacheckout/urls.py

Handles the URL configuration of the sumiacheckout app. It enables the user to navigate easily on the app. We shall have four URL patterns: checkout, payment, checkout_success, and promotion code.

Sumiacheckout/views.py

We shall import different modules:

from django.contrib.auth.mixins import LoginRequiredMixin-This module is used to limit the user to access associated views unless he logs in.

from django.contrib.messages.views import SuccessMessageMixin-This module is for sending success messages from view to the html page.

from django. views. generic import UpdateView, View-this model is used for displaying a list of records from a specific database table, showing all the details of a specific entry of a database.

from django.contrib import messages-This is used to send up messages from the app views to the html pages.

from django.shortcuts import redirect,get_object_or_404-This is the module used for rendering the HTML pages to the customers.

from django. utils. crypto import get_random_string-this module is used for generating random alphanumeric strings

from django.conf import settings– this module is used to import the first module named settings.py in the system path

We shall import from apps models ShippingAddressForm, PromotionCodeForm, PromotionCode, ShippingAddress, Payment, and order from sumiacart app models. We shall also import stripe from the stripe package to handle payments.

It will consist of different classes/views with different functionalities.

CheckoutView-It will enable the user to order. It will display the ordered items, shipping address, shipping address form, and promotion code form if successful the user will be redirected to the checkout to pay.

PaymentView-for you to access this form you will be required to log in. It is where the user can pay for the products using stripe. If there is an error maybe from the card the customer gets the message Payment could not be made or internal server error and then redirected back to the homepage where there is a display of products. If the payment is successful the customer is redirected to the checkout and gets a confirmatory message confirming the payment was successful.

ShippingAddressUpdateView-This logic is for updating the shipping address form. When the update is successful the user gets a notification that the address has been updated successfully.

PromoCodeView-It enables the customer to apply the promo code provided. If the customer uses a promo code twice he will receive a message that the promo code has already been applied, if the customer provides an invalid code he will be told that the provided code does not exist. If the promo code is applied successfully the customer is redirected to the checkout.

Here is the code:

Sumiaproducts

Let’s now look at the functionalities of the sumiaproducts app which deals with the products being listed on the site. Products will be added by the admin.

Sumiaproducts/admin.py

In this file admin.py, we register our two models: category and product.

Sumiaproducts/apps.py

Contains the app configuration.

Sumiaproducts/models.py

We shall be importing different modules:

from django.db import models – It will be used to convert a python class to a database table

from django. shortcuts import reverse-It will be used to resolve a url name

from PIL import Image-It will be used to import image class from the pillow package.

Now let’s look at different models created:

Category class-this This will help us in holding the category in which the product lies. It will be requesting the name field only. The name column will be used for storing the name of the category in the database.

Product Class-This model will hold the description of the product being posted. It will have the following fields: name, description, price, category and the image to be uploaded. The name column will store the name of the category in the database, the description column will store the details of the item in the database, the price column will store the price of an item in the database, image column will store the images of the items uploaded and category column will store the category in which an item falls in the database.

Sumiaproducts/urls.py

It will contain the url configuration of the app. We shall import the homepage and ProductdetailView from the models.

It will have two urls:

Home-page-for homepage url

Product-detail- the url to show the details of the product posted.

Sumiaproducts/views.py

It will handle the request of the app. We shall import products from the models of the project.

It will have different classes:

HomePage class-It will be displaying the homepage of our project. It will be displaying all the images posted on the site.

ProductDetailView class-It will be used to display all the details about the project from name, description, price, category e.t.c

Now let’s create a superuser where he will be responsible for creating categories, items, promotion codes, refunds, seeing orders, payments e.t.c. We shall create a superuser by typing the following on the terminal: python manage.py createsuperuser

It will prompt you for username, email, and password which you will fill. After creating the user successfully log into http://127.0.0.1:8000/admin and perform different tasks.

Creating the Apps Templates

This helps in making the app data to be displayed to the customers.

Cart. html-it handles the app components: displays product, quantity, price, amount, total cost and redirect links.

Order_list.html-It shows the number of orders made by the customer. It displays the order id, date of payment and products ordered.

Refund.html- It displays the form that is filled when a customer wants to ask for a refund.

Base.html- this is the HTML page that will be inherited by all HTML templates.

Home.html-It is the default home page for sumiasell app

Messages.html-for displaying the messages

Navbar.html-contains the navigation bar of the app

Product_details.html-It shows the details of the product posted.

checkout.html-for rendering the checkout page

payment.html-HTML page for handling payments

profile.html-for filling the customers profile

shipping_address_form.html-html page where customer fills his shipping details

success.html-Showing the success message after placing order

Creating Static files

We shall create static files for some apps.

Sumiacheckout/checkout

Stripe_payment.css-handles the appearance of the stripe checkout

Stripe_payment.js-handles the functioning of the stripe payment.

Sumiaproducts/products

Main.js-for managing cookies, alerts.

Conclusion

In this tutorial, we have seen how we can build a simple e-commerce site. You can improve the site by integrating other payment methods like MPESA, bitcoin. You can also improve the dashboard using chart.js and maybe marketing integration with mail clients like convert kit. Instead of using Gmail as a Django email client, you can use mailgun, SendGrid as an alternative to sending emails. We can also have a statistics dashboard and maybe integration of a live chat for customer experience.

Here is the repo to the platform.

Quick guide

If you just want to clone the project and get it up running, below is how to do:

  1. Clone it: git clone https://github.com/Ericksonodiaga/ecommerce
  2. Cd into it: cd sumiasell
  3. Create a venv: python3 -m venv venv
  4. Activate venv: On Mac/Linux: source venv/bin/activate On Windows: venv\Scripts\activate
  5. Install the requirements: pip install -r requirements.txt
  6. Create DB :python manage.py makemigrations
  7. Apply DB Changes: python manage.py migrate
  8. Run the server: python manage.py runserver
  9. Navigate to the site: http://127.0.0.1:8000
  10. Follow the instructions on the about page to start using the site

0 Shares:
You May Also Like