E-commerce Website using Django - GeeksforGeeks

04 Jul, 2021
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 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.
Django framework and SQLite database which comes by default with Django.
Knowledge of Python and basics of Django Framework.
Customer Interface:
Customer shops for a productCustomer changes quantityThe customer adds an item to the cartCustomer views cartCustomer checks outCustomer sends order
Customer shops for a product
Customer changes quantity
The customer adds an item to the cart
Customer views cart
Customer checks out
Customer sends order
ER-diagram for Customer
Use-Case diagram for Customer
Admin Interface:
Admin logs inAdmin inserts itemAdmin removes itemAdmin modifies item
Admin logs in
Admin inserts item
Admin removes item
Admin modifies item
ER-diagram for Admin
Use-Case diagram for Admin
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.
This file contains all the URL patterns used by the website
Python3
from django.contrib import adminfrom django.urls import path, includefrom django.conf.urls.static import staticfrom . import settings  urlpatterns = [    path('admin/', admin.site.urls),    path('', include('store.urls'))] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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.
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
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
Python3
from django.db import modelsfrom .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()
Python
from django.db import modelsfrom .product import Productsfrom .customer import Customerimport 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')
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 adminfrom django.urls import pathfrom .views.home import Index, storefrom .views.signup import Signupfrom .views.login import Login, logoutfrom .views.cart import Cartfrom .views.checkout import CheckOutfrom .views.orders import OrderViewfrom .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. 
Python3
from django.shortcuts import render, redirect, HttpResponseRedirectfrom store.models.product import Productsfrom store.models.category import Categoryfrom 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)
Python3
from django.shortcuts import render, redirect, HttpResponseRedirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom 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')
Python3
from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import make_passwordfrom store.models.customer import Customerfrom 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
Python3
from django.db import modelsfrom .product import Productsfrom .customer import Customerimport 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')
Python3
from django.shortcuts import render, redirect  from django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import View  from store.models.product import Productsfrom 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')
Python3
from django.shortcuts import render, redirectfrom django.contrib.auth.hashers import check_passwordfrom store.models.customer import Customerfrom django.views import Viewfrom store.models.product import Productsfrom store.models.orders import Orderfrom 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})
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.
GitHub Link to the project 
Django-Projects
ProGeek 2021
Python Django
ProGeek
Project
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Build a Simple Note Android App using MVVM and Room Database?
Handwritten Digit Recognition using Neural Network
AI Driven Snake Game using Deep Q Learning
Rock, Paper, Scissor game - Python Project
Twitter Sentiment Analysis WebApp Using Flask
SDE SHEET - A Complete Guide for SDE Preparation
XML parsing in Python
Python | Simple GUI calculator using Tkinter
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python