How to Add Cart in a Web Page using Django?
Last Updated :
22 May, 2025
A shopping cart allows users to collect and manage items they want to purchase before proceeding to checkout. We will build a simple shopping cart using Django and learn how to create models, views, templates and URLs to add, view and remove items from the cart—step by step.
Create Django Project and App
Prerequisites:
To start the project and app use this command
django-admin startproject ecommerce
cd ecommerce
python manage.py startapp cart
Now add this app to the 'settings.py'.

Define Models in models.py
Your database schema is the foundation of the app. We'll create two models:
- Product: Represents items available for sale.
- CartItem: Represents individual product items added to a user's cart.
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}'
Register Models in Admin
Register your models so you can add/edit products and cart items via Django’s admin interface:
Python
from django.contrib import admin
from .models import Product, CartItem
admin.site.register(Product)
admin.site.register(CartItem)
Create Views in views.py
The views will handle displaying products, managing the cart, adding/removing items and rendering appropriate templates.
- 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.
Set Up Templates for User Interface
Product List - index.html
Displays all products with their image, description, price and an Add to Cart button.
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 View - cart.html
Shows the current items in the cart with quantity, price and a remove option, along with the total cost.
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>
In cart/urls.py, map URLs to the views:
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'),
]
Include these URLs in the main ecommerce/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)
Configure Django to serve static and media files during development. In your project's settings.py file, add the following:
Python
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media"
Apply Migrations and Run the Server
Generate and apply database 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.

Output


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 in
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 ?
In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 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 Fl
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. What is the Paginator Class?The P
4 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 ?
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 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 create a new project in Django using Firebase Database?
Django is a Python-based web framework that allows you to quickly create efficient web applications. If you are new to Django then you can refer to Django Introduction and Installation. Here we are going to learn How to create a Django project using Firebase as Database . How to create a new projec
3 min read