Add Items To Shopping Cart Django Python

When I first started building e-commerce applications with Django, one of the core features I needed was a shopping cart. Adding items to a cart might seem simple at first, but as you dig deeper, you realize there are several ways to implement it depending on your project’s needs.

In this article, I’ll share my firsthand experience on how to add items to a cart in Django. I’ll cover a simple, effective approach that you can customize for your projects.

Let’s get right in!

Understand the Cart Concept in Django

Before jumping into the code, it’s important to understand what a shopping cart entails:

  • A cart stores the products a user wants to buy.
  • It tracks the quantity of each product.
  • It persists across user sessions (either logged in or anonymous).
  • It allows users to add, update, or remove items.

In Django, you can implement a cart using sessions, database models, or a combination of both. For this tutorial, I’ll demonstrate an easy method using the session to store cart data, which works well for most small to medium-sized projects.

Read Convert HTML Page to PDF using Django in Python

Method 1: Add Items to Cart Using Django Sessions

Using sessions is a quick way to store cart data without creating extra database tables. The cart data is stored as a dictionary in the user’s session.

Step 1: Set Up Your Django Project and App

Assuming you have Django installed, start by creating a new project and app:

django-admin startproject myshop
cd myshop
python manage.py startapp store

Add 'store' to your INSTALLED_APPS in settings.py.

Step 2: Create a Simple Product Model

In store/models.py, define a basic product model that includes product name, description, and price:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=8, decimal_places=2)

    def __str__(self):
        return self.name

Run migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Check out Get URL Parameters in Django

Step 3: Create Views to Add Items to Cart

In store/views.py, implement the logic to add items to the cart stored in the session:

from django.shortcuts import get_object_or_404, redirect, render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'store/product_list.html', {'products': products})

def add_to_cart(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    cart = request.session.get('cart', {})

    if str(product_id) in cart:
        cart[str(product_id)] += 1
    else:
        cart[str(product_id)] = 1

    request.session['cart'] = cart
    return redirect('cart_detail')

def cart_detail(request):
    cart = request.session.get('cart', {})
    cart_items = []
    total_price = 0

    for product_id, quantity in cart.items():
        product = get_object_or_404(Product, id=product_id)
        item_total = product.price * quantity
        total_price += item_total
        cart_items.append({
            'product': product,
            'quantity': quantity,
            'item_total': item_total,
        })

    return render(request, 'store/cart_detail.html', {'cart_items': cart_items, 'total_price': total_price})

Step 4: Define URLs for Your Views

In store/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('add-to-cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
    path('cart/', views.cart_detail, name='cart_detail'),
]

Include these URLs in your main urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('store.urls')),
]

Read Python Django Length Filter

Step 5: Create Templates

Create a templates/store directory and add the following HTML templates:

product_list.html

<!DOCTYPE html>
<html>
<head>
    <title>Products</title>
</head>
<body>
    <h1>Available Products</h1>
    <ul>
        {% for product in products %}
            <li>
                <strong>{{ product.name }}</strong> - ${{ product.price }}<br>
                {{ product.description }}<br>
                <a href="{% url 'add_to_cart' product.id %}">Add to Cart</a>
            </li>
        {% endfor %}
    </ul>
    <a href="{% url 'cart_detail' %}">View Cart</a>
</body>
</html>

cart_detail.html

<!DOCTYPE html>
<html>
<head>
    <title>Your Cart</title>
</head>
<body>
    <h1>Your Shopping Cart</h1>
    {% if cart_items %}
        <ul>
            {% for item in cart_items %}
                <li>
                    {{ item.product.name }} - Quantity: {{ item.quantity }} - Total: ${{ item.item_total }}
                </li>
            {% endfor %}
        </ul>
        <p><strong>Total Price: ${{ total_price }}</strong></p>
    {% else %}
        <p>Your cart is empty.</p>
    {% endif %}
    <a href="{% url 'product_list' %}">Continue Shopping</a>
</body>
</html>

Step 6: Test Your Cart

  • Run the server with python manage.py runserver.
  • Navigate to http://127.0.0.1:8000/ to see the product list.
  • Click “Add to Cart” to add items.
  • View your cart by clicking “View Cart.”

You can refer to the screenshot below to see the output.

django cart
django shopping cart tutorial

Check out Django for Loop

Method 2: Use a Cart Model for Persistent Storage

For more complex applications, especially where you want carts to persist across devices or sessions, creating dedicated database models for the cart and cart items is better.

Step 1: Define Cart and CartItem Models

In store/models.py:

from django.conf import settings
from django.db import models

class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

class CartItem(models.Model):
    cart = models.ForeignKey(Cart, related_name='items', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)

    def get_total_price(self):
        return self.product.price * self.quantity

Run migrations:

python manage.py makemigrations
python manage.py migrate

Step 2: Manage Cart in Views

In store/views.py:

from django.contrib.auth.decorators import login_required

@login_required
def add_to_cart(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    cart, created = Cart.objects.get_or_create(user=request.user)
    cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)

    if not created:
        cart_item.quantity += 1
        cart_item.save()

    return redirect('cart_detail')

@login_required
def cart_detail(request):
    cart = Cart.objects.filter(user=request.user).first()
    cart_items = cart.items.all() if cart else []
    total_price = sum(item.get_total_price() for item in cart_items)

    return render(request, 'store/cart_detail.html', {'cart_items': cart_items, 'total_price': total_price})

Read Python Django Group By

Step 3: Update Templates

Modify cart_detail.html to use the new cart item structure:

{% for item in cart_items %}
    <li>
        {{ item.product.name }} - Quantity: {{ item.quantity }} - Total: ${{ item.get_total_price }}
    </li>
{% endfor %}

Adding items to a cart in Django can be as simple or as complex as your project requires. Using sessions is a quick way to get started, while database-backed carts provide more flexibility and persistence.

From my experience, starting with the session-based cart helps you prototype quickly. Once your app grows, migrating to a model-based cart system is a natural next step.

Remember to tailor the implementation to your users’ needs, especially if you expect them to log in and want their carts saved across devices.

I hope this guide makes your Django e-commerce journey smoother.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.