Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
How to Build a Web App using Flask and SQLite in Python
Next article icon

How to Add Cart in a Web Page using Django?

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Adding a shopping cart to a web page using Django is a crucial step when building an e-commerce website or any other application that involves online transactions. A shopping cart allows users to collect and manage items they want to purchase before proceeding to checkout. In this tutorial, we'll walk you through the process of creating a basic shopping cart using Django, including all the necessary files and HTML templates.

Steps Add Cart in a Web Page using Django

Setup and Installation

To install Django follow these steps.

To start the project use this command

django-admin startproject ecommerce
cd ecommerce

To start the app use this command.

python manage.py startapp cart

Now add this app to the 'settings.py'.

Screenshot-2023-10-06-170834

model.py: Here we have created a Product table with name, description, and price, image field in the table. Whereas, The CartItem model represents items added to the shopping cart by users.

Python
from django.db import models from django.contrib.auth.models import User class Product(models.Model):     name = models.CharField(max_length=100)     description = models.TextField(null=True)     price = models.DecimalField(max_digits=10, decimal_places=2)     image = models.ImageField(upload_to='products/')      def __str__(self):         return self.name  class CartItem(models.Model):     product = models.ForeignKey(Product, on_delete=models.CASCADE)     quantity = models.PositiveIntegerField(default=0)     user = models.ForeignKey(User, on_delete=models.CASCADE)     date_added = models.DateTimeField(auto_now_add=True)      def __str__(self):         return f'{self.quantity} x {self.product.name}' 

admin.py: Here we are registering our table in the admin.

Python
from django.contrib import admin from .models import Product, CartItem  admin.site.register(Product) admin.site.register(CartItem) 

views.py: The cart/views.py code contains views that handle various aspects of the shopping cart functionality in a Django application. Here's a brief explanation of each view:

  • product_list(request): This view fetches a list of products from the database and renders a template to display them. Each product is shown with its name, price, and an "Add to Cart" button.
  • view_cart(request): This view displays the contents of the shopping cart. It retrieves the cart items associated with the current user, calculates the total price of the items in the cart, and then renders a template to display the cart items along with the total price.
  • add_to_cart(request, product_id): When a user clicks the "Add to Cart" button on a product, this view is triggered. It adds the selected product to the user's cart. If the product is already in the cart, it increments the quantity. It then redirects the user to the cart view to display the updated cart contents.
  • remove_from_cart(request, item_id): This view handles the removal of an item from the cart. It takes the item's ID as a parameter, retrieves the corresponding cart item, and deletes it from the database. After removal, it redirects the user to the cart view to reflect the updated cart.
Python
from django.shortcuts import render, redirect from .models import Product, CartItem  def product_list(request):     products = Product.objects.all()     return render(request, 'myapp/index.html', {'products': products})  def view_cart(request):     cart_items = CartItem.objects.filter(user=request.user)     total_price = sum(item.product.price * item.quantity for item in cart_items)     return render(request, 'myapp/cart.html', {'cart_items': cart_items, 'total_price': total_price})  def add_to_cart(request, product_id):     product = Product.objects.get(id=product_id)     cart_item, created = CartItem.objects.get_or_create(product=product,                                                         user=request.user)     cart_item.quantity += 1     cart_item.save()     return redirect('cart:view_cart')  def remove_from_cart(request, item_id):     cart_item = CartItem.objects.get(id=item_id)     cart_item.delete()     return redirect('cart:view_cart')   def home(request):     return HttpResponse('Hello, World!') 

Adding a cart to a Django web page is a crucial skill for e-commerce apps. If you're looking to build more complex applications, the Django Web Development Course will guide you through advanced concepts.

Creating GUI

index.html: It is used to display a list of products with "Add to Cart" buttons.

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Product Catalog</title>     <style>         /* Add CSS styles for flex container and items */         .product-list {             display: flex;             flex-wrap: wrap; /* Allow items to wrap to the next row if necessary */             justify-content: space-between; /* Space items evenly along the main axis */             list-style: none; /* Remove list styles */             padding: 0;         }          .product-item {             flex: 1; /* Grow to fill available space evenly */             max-width: 30%; /* Limit item width to avoid overcrowding */             margin: 10px; /* Add spacing between items */             border: 1px solid #ccc; /* Add a border for visual separation */             padding: 10px;             text-align: center;         }          /* Style the "Buy Now" button */         .buy-now-button {             display: block;             margin-top: 10px;             background-color: #007bff;             color: #fff;             text-decoration: none;             padding: 5px 10px;             border-radius: 5px;         }     </style> </head> <body>     <h1>Product Catalog</h1>          <ul class="product-list">         {% for product in products %}             <li class="product-item">                 <img src="{{ product.image.url }}" alt="{{ product.name }}" width="200" height="150">                 <h2>{{ product.name }}</h2>                 <p>{{ product.description }}</p>                 <p>Price: ${{ product.price }}</p>                 <a href="#" class="buy-now-button">Buy Now</a>                 <a class="buy-now-button" href="{% url 'cart:add_to_cart' product.id %}">Add to Cart</a>              </li>         {% endfor %}     </ul> </body> </html> 

cart.html: Display the shopping cart, allow item removal, and calculate the total price.

HTML
<!-- cart/cart.html -->  <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Document</title>     <style>         /* Add CSS styles for flex container and items */         .product-list {             display: flex;             flex-wrap: wrap; /* Allow items to wrap to the next row if necessary */             justify-content: space-between; /* Space items evenly along the main axis */             list-style: none; /* Remove list styles */             padding: 0;         }          .product-item {                          flex: 1; /* Grow to fill available space evenly */              /* Limit item width to avoid overcrowding */             margin: 10px; /* Add spacing between items */             border: 1px solid #ccc; /* Add a border for visual separation */             padding: 10px;             text-align: center;         }          /* Style the "Buy Now" button */         .buy-now-button {             display: block;             margin-top: 10px;             background-color: #007bff;             color: #fff;             text-decoration: none;             padding: 5px 10px;             border-radius: 5px;         }     </style> </head>  <body>      <h1>Your Shopping Cart</h1>      <div class="product-list">           {% for item in cart_items %}     <div class="product-item">         <p>{{ item.product.name }} ({{ item.quantity }})</p>         <p>Price: ${{ item.product.price }}</p>         <a href="{% url 'cart:remove_from_cart' item.id %}">Remove</a>     </div>     {% empty %}     <p>Your cart is empty.</p>     {% endfor %}      </div>      <p>Total Price: ${{ total_price }}</p>      <a href="{% url 'cart:product_list' %}">Continue Shopping</a>  </body>  </html> 

urls.py: Define the URL patterns in the urls.py file of the cart app to map views to URLs.

Python
from django.urls import path from . import views  app_name = 'cart'  urlpatterns = [     path('', views.product_list, name='product_list'),     path('/home', views.home, name='home'),     path('cart/', views.view_cart, name='view_cart'),     path('add/<int:product_id>/', views.add_to_cart, name='add_to_cart'),     path('remove/<int:item_id>/', views.remove_from_cart, name='remove_from_cart'), ] 

urls.py: Add the necessary URL patterns for serving media files in your project's urls.py.

Python
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings  urlpatterns = [     path('admin/', admin.site.urls),     path('', include('cart.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

Setting Up Static and Media Files

Configure Django to serve static and media files during development. In your project's settings.py file, add the following:

# Static files (CSS, JavaScript, images)
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
# Media files (uploaded user files)
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media"

Deployement of the Project

Run these commands to apply the migrations:

python manage.py makemigrations 
python manage.py migrate

Run the server with the help of following command:

python manage.py runserver

Now, Go to the http://127.0.0.1:8000/admin/ and add the Images, name and its description.

Screenshot-from-2023-10-05-01-05-20

Output

Screenshot-from-2023-10-05-01-09-41


Screenshot-from-2023-10-05-01-11-49



Next Article
How to Build a Web App using Flask and SQLite in Python

A

amitgupm1wy
Improve
Article Tags :
  • Project
  • Geeks Premier League
  • Django
  • Python Django
  • Geeks Premier League 2023

Similar Reads

  • How to Create a Basic Project using MVT in Django ?
    Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To initi
    2 min read
  • How to make an API-based carousel using Django?
    In web development, carousels are widely used to showcase a dynamic set of images or content interactively. They prove popular for displaying products, portfolios, or any content that benefits from an engaging visual presentation. This tutorial will guide you through the process of creating an API-b
    10 min read
  • How to Create an App in Django ?
    Prerequisite - How to Create a Basic Project using MVT in Django? Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. This article will take you through how to create a basic app and add functionalities
    4 min read
  • How to Build a Web App using Flask and SQLite in Python
    Flask is a lightweight Python web framework with minimal dependencies. It lets you build applications using Python libraries as needed. In this article, we'll create a Flask app that takes user input through a form and displays it on another page using SQLite. Run the following commands to install F
    3 min read
  • A Guide to Sending Data Using Cache in Django
    In this article, we aim to comprehensively explore the functionality of sending data using cache in Django by providing a well-structured example implementation. Through this practical demonstration, we will delve into the intricacies of Django's caching system, ensuring that you gain a clear unders
    6 min read
  • How to add Pagination in Django Project?
    Pagination system is one of the most common features in  blogs, search engine , list of result etc. Seeing the popularity of pagination system django developers have build a Paginator class so that web developers do not have to think of the logic to make paginators.  Paginator Class live in django/c
    5 min read
  • How to Render Data in Django
    Django's render() function is a fundamental tool for building dynamic web applications. It simplifies the process of combining HTTP requests with HTML templates and dynamic data, making it easier for developers to create interactive and data-driven web pages.  What is render()?In Django, the render(
    3 min read
  • How to create a form using Django Forms ?
    Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model
    3 min read
  • Creating a JSON Response Using Django and Python
    In Django, we can give responses to the front end in several ways. The simplest way to render a template or send a JSON response. JSON stands for JavaScript Object Notation and is widely used for data transfer between front-end and back-end and is supported by different languages and frameworks. In
    4 min read
  • How to add AMP to Django Project?
    A blog mostly needs content but that doesn't mean, your blog will be on top of Google search. For this you will need Speed, Security, user base and first of all search engines need to know that your blog exists. We will add AMP for speed.  This article is in continuation of Blog CMS Project in Djang
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences