The Wayback Machine - https://web.archive.org/web/20241001064123/https://www.geeksforgeeks.org/e-commerce-website-using-django/
Open In App

E-commerce Website using Django

Last Updated : 21 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 build a Django e-commerce web application, it is necessary to study and understand many technologies.

Technologies and Required Skills Used in the Project

Django E-commerce Web Application

Scope: The scope of the project will be limited to some functions of the e-commerce website. It will display products, and 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 a great future scope. The project also provides security with the use of login ID and passwords, so that no unauthorized users can access your account. The only authorized person who has the appropriate access authority can access the software.

ER Diagram for E-commerce Website

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

ER-diagram for Customer

Use-Case diagram for Customer

Admin Interface

  1. Admin logs in
  2. Admin inserts item
  3. Admin removes item
  4. Admin modifies item

ER-diagram for Admin

Use-Case diagram for Admin

Step by Step Implementation

  • Create Normal Project: Open the IDE and create a normal project by selecting File -> New Project.
  • 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 -m pip install django command
  • Check Installed Django version: To check the installed Django version, you can run the python -m django -version command as shown below.
  • Create Django Project: When we execute django-admin startproject command, then it will create a Django project inside the normal project which we already have created here. django-admin startproject ProjectName.
  • Check Python3 version: python3 –version
  • Run Default Django webserver:- Django internally provides a default webserver where we can launch our applications. python manage.py runserver command in terminal. By default, the server runs on port 8000. Access the webserver at the highlighted URL.

Open the project folder using a text editor. The directory structure should look like this:

Project Structure

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.py: 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 the fields required by each model.

category.py: This is a Django model for a “Category” that includes a name field with a maximum length of 50 characters. It also has a static method get_all_categories() to retrieve all the categories from the database. The __str__ method is defined to return the name of the category when it’s converted to a string.

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: This is a Django model for a “Customer” with fields for name, phone, email, and password. It includes methods to register, retrieve customers by email, and check if a customer exists.

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 : This is a Django model for “Products” with fields for name, price, category, description, and image. It also includes static methods to retrieve products by ID, retrieve all products, and retrieve products by category ID.

Python3




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: This is a Django model for “Order” with fields for product, customer, quantity, price, address, phone, date, and status. It also includes methods to place an order and get orders by customer ID.

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.py: 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. 

Python3




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: This is a Django view for handling an online store. It includes methods for displaying the store’s index, adding or removing items from the cart, and rendering the store’s product listings. The view also uses Django sessions to manage the user’s shopping cart.

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: This Django view handles user authentication, including login and logout. It allows users to log in with their email and password, and upon successful login, it stores the customer’s ID in the session. The Login view also supports a return URL, which can be used to redirect users to a specific page after successful login.

Additionally, there is a logout function to clear the user’s session and log them out, redirecting them to the login page.

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: This Django view handles user registration (sign-up). Users can input their first name, last name, phone, email, and password. It performs several validation checks to ensure that the entered data is correct. If validation is successful, the password is hashed for security, and the user is registered. If there are any errors, they are displayed on the sign-up page.

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: This Django model represents an “Order” in an e-commerce application. It has fields such as “product” and “customer” which are foreign keys to the “Products” and “Customer” models, respectively. The model stores information about the ordered product, including its quantity, price, delivery address, and contact phone number. The “date” field stores the order date, and the “status” field indicates whether the order is completed or not.

The class provides methods for placing an order and retrieving orders by a specific customer ID, ordered by date in descending order.

Python3




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: The “CheckOut” view in a Django e-commerce application handles the checkout process. It collects the customer’s delivery address and phone number via a POST request. It also retrieves the customer’s ID and their shopping cart from the session. The view creates order records for the selected products, including product details, customer information, prices, and quantities. After processing the order, it clears the shopping cart in the session and redirects the user to the “cart” page.

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
  
  
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: The “OrderView” view in a Django e-commerce application handles displaying the orders for a logged-in customer. It retrieves the customer’s ID from the session and uses it to fetch the customer’s orders from the database. The view then renders an “orders.html” template, passing the list of orders to be displayed. This allows the customer to view their order history. The “auth_middleware” is used to ensure that only authenticated customers can access this view.

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


Output 

The project already includes a lot of features. The main beneficiaries are both customers and administrators who take longer to behave online. In addition, additional features can be identified and incorporated in the future. It will take more time and effort to understand the need and adjust it to a computerized system to accommodate additional features.



Previous Article
Next Article

Similar Reads

E-commerce Website using Tailwind and React using Django
Our e-commerce website, "ECOM," aims to offer users a smooth online shopping experience. We use Tailwind CSS for styling, React for interactive user interfaces, and Django for a strong backend. Shopify features a wide range of products across different categories, with functionalities like user authentication, product search, shopping cart manageme
6 min read
Django project - Creating a Basic E-commerce Website for Displaying Products
Project Title - Basic Ecommerce Website using Django Django is a powerful framework based on python. Here we will see how to create a basic e-commerce website in Django. This project includes storing products in the database and show them on the website. Refer to the following articles to check how to create a project and an app in Django. How to C
3 min read
E-commerce Website using MERN Stack
The project is an E-commerce website built using the MERN (MongoDB, Express.js, React, Node.js) stack. It provides a platform for users to view and purchase various products. The server-side (Node.js with Express) manages the API for product data stored in a MongoDB database. The client-side (React) handles the user interface and interacts with the
7 min read
E-commerce Product Catalog using Django
Django is an excellent choice for building a robust product catalog. Django, a high-level Python web framework, provides a solid foundation for creating feature-rich and scalable e-commerce websites. In this article, we will explore how to build an e-commerce product catalog using Django. E-commerce Product Catalog using DjangoTo install Django fol
4 min read
Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read
Hosting Your Django Website on a CentOS VPS
Hosting any website/web application on a live server can sometimes become difficult if proper steps are not taken while deploying it. There are mainly 3 different types of hosting: Shared Hosting - Usually used for small (single page) websites with limited traffic.VPS Hosting - VPS ( Virtual Private Server ) hosting is used for websites with good a
5 min read
How to Integrate Custom Rich Text-Editor in Your Django Website?
In this article, we will implement tinymce text editor in our Django application. What is django-tinymce? django-tinymce is a Django application that contains a widget to render a form field as a TinyMCE editor. Features :- Use as a form widget or with a view.Enhanced support for content languages.Integration with the TinyMCE spellchecker.Enables p
3 min read
Django - Creating a Multi-Page Website
Django is a python based open-source framework used for web development. Django allows the usage of the M-T-V (Model-Templates-View) architectural pattern for the creation and deployment of a functional website. This article aims at creating a multipage personal profile website using Django to explain all the main concepts and aspects of the Django
8 min read
Add a Favicon to a Django Website
A Favicon (short for "favorite icon") is a small icon displayed on the browser's tab right next to page titles. In addition, adding a favicon to your Django app will help with brand recognition and provide a better user experience since people can easily identify their website. Adding Favicon to Static FilesTo place a favicon in your Django project
3 min read
Django vs Spring Boot: Which is Better For Your Website
In the fast-paced world of web development, picking the right framework is like choosing the base for a tall building. It's super important! Imagine you're picking the perfect foundation for a skyscraper. Now, there are two big contenders in this web development game: Django and Spring Boot. They're like your trusty sidekicks, each with their own c
9 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
How to Fix Django "ImportError: Cannot Import Name 'six' from 'django.utils'"?
After Django 3.0, django.utils.six was removed. The "ImportError: Cannot Import Name 'six' from 'django.utils'" error occurs because of the dependency issue. This happens because when the project tries to use something that’s no longer available. Don’t worry—it’s easy to fix. We’ll explain why this error happens and give you simple steps to solve i
3 min read
Fashion Store E-Commerce using MERN Stack
This E-commerce site project uses the MERN (MongoDB, Express.js, React.js, and Node.js) stack to deliver a fully functional online shopping experience. Users can explore a diverse range of products, filter items based on criteria like price range and product type, add selected items to their cart and view the total price. Output Preview: Let us hav
7 min read
Create an E-commerce App using React-Native
An E-commerce app using react native is an application designed to facilitate online buying and selling of goods and services. These apps aim to provide a digital platform for businesses to showcase their products or services and for consumers to browse, compare, and purchase items without the need to visit physical stores. In this article, you wil
5 min read
E-commerce Dashboard with NextJS
This project is an E-commerce Dashboard built with Next.js, providing features such as a dynamic sidebar, responsive navigation, order analytics, and most sold items of the week. It shows various features such as product analytics, order management, and user interaction. Output Preview: Prerequisites:Node.jsJavaScriptNext.jsApproachUtilize React an
11 min read
E-Commerce Web UI
Designing an e-commerce website while following the design principles is crucial as it involves tasks ranging from designing a compatible header & footer for the website along with different other attributes such as the About us page, viewing different products, ordering different products, adding them to the cart & viewing individual produ
4 min read
Website Blocker Using Python
This is real world program which blocks certain distracting website like Facebook, Youtube etc during your work hours. About the program : What we are going to in this program is that we will pass the link of websites which you think is distracting and the time that you are working on your computer and program will block those website. Program Arch
3 min read
Project Idea | Website Generator using Facebook/Instagram Page
Project Title: Website Generator using their Facebook/Instagram Page Introduction: The Idea is to provide a website for those students who make their Facebook /Instagram page or group and want to shift their data on a static website and want to be a good blogger. So, this framework provides them with a website without doing such painful work. Featu
1 min read
Scrape Tables From any website using Python
Scraping is a very essential skill for everyone to get data from any website. Scraping and parsing a table can be very tedious work if we use standard Beautiful soup parser to do so. Therefore, here we will be describing a library with the help of which any table can be scraped from any website easily. With this method you don't even have to inspec
3 min read
Launch Website URL shortcut using Python
In this article, we are going to launch favorite websites using shortcuts, for this, we will use Python's sqlite3 and webbrowser modules to launch your favorite websites using shortcuts. Both sqlite3 and webbrowser are a part of the python standard library, so we don't need to install anything separately. The best part about this is that because we
3 min read
How to Check Loading Time of Website using Python
In this article, we will discuss how we can check the website's loading time. Do you want to calculate how much time it will take to load your website? Then, what you must need to exactly do is subtract the time obtained passed since the epoch from the time obtained after reading the whole website. Stepwise Implementation:Step 1: Import the librari
3 min read
Automated Website Scraping using Scrapy
Scrapy is a Python framework for web scraping on a large scale. It provides with the tools we need to extract data from websites efficiently, processes it as we see fit, and store it in the structure and format we prefer. Zyte (formerly Scrapinghub), a web scraping development and services company, currently maintains it. What is a Web Crawler (Web
5 min read
How to Scrape Multiple Pages of a Website Using Python?
Web Scraping is a method of extracting useful data from a website using computer programs without having to manually do it. This data can then be exported and categorically organized for various purposes. Some common places where Web Scraping finds its use are Market research & Analysis Websites, Price Comparison Tools, Search Engines, Data Col
6 min read
Create a Website Alarm Using Python
We use Bookmarks to remember the important websites which we think we will use them very often in future. Here's a simple python code which takes the URL of the website as its first input and the time you want to open it as the second input. As the time reaches your given value of the time, it'll open the URL that you requested in the web browser a
2 min read
Build Blog website using Flask
In this article, we'll explore how to build a dynamic blog website using Flask, a lightweight and versatile Python web framework. Flask provides developers with the tools needed to create robust web applications, and its simplicity makes it an excellent choice for beginners and experienced developers alike. Requirements Basics of HTML & CSSBoot
15+ min read
Summarizer Website using MEAN Stack
This article aims to develop a project using MEAN stack which will work as a summarizer website. MEAN stack technologies include MongoDB, AngularJS, NodeJS, and Express. It will give you a thorough understanding of how to create a MEAN stack application end to end from backend to frontend including the user authentication feature. Output Preview: L
15+ min read
Create A Bookmark Organizer For Website Using Flask
This article explains how to make a tool called a Bookmark Organizer with Flask for a website. With this tool, we can add, create, update, delete, and edit bookmarks easily. We just need to input the title and link, and we can save them. Then, we can click on the link anytime to visit the website. What is a Bookmark Organizer?A Bookmark Organizer i
5 min read
Create A Real Estate Website Using React and Tailwind CSS
A Real Estate Website built with React JS and Tailwind CSS is a modern and responsive web application that is designed to showcase real estate listings. It typically includes features such as OnSale property, a Features section, and a Contact Us section. The website is created using React JS, which is a popular JavaScript library used for building
9 min read
Practice Tags :