Create a Shopping Cart with Django | Easy Guide for Beginners

Faraz

By Faraz - July 30, 2024

Learn how to create a shopping cart using Django with our easy guide. Step-by-step instructions and tips for beginners to build a functional cart for your website.


create-a-shopping-cart-with-django-easy-guide-for-beginners.webp

Creating a shopping cart is a crucial feature for any e-commerce website. If you're looking to add a shopping cart to your website using Django, you're in the right place. This guide will walk you through the process of building a shopping cart from scratch. We’ll cover everything from setting up your Django project to adding products, managing quantities, and handling user interactions. Whether you're a beginner or just need a refresher, this tutorial will provide clear, step-by-step instructions to help you create a functional and user-friendly shopping cart.

Prerequisites

Before we dive in, make sure you have a basic understanding of Django and web development. You'll need the following tools and libraries installed on your machine:

  • Python (version 3.6 or higher)
  • Django (version 3.0 or higher)
  • A text editor or IDE (such as VS Code or PyCharm)
  • Basic knowledge of HTML and CSS

Setting Up the Development Environment

Installing Django

Before starting, ensure you have Python installed. You can install Django using pip:

pip install django

Creating a new Django project

Create a new Django project using the following command:

django-admin startproject shoppingcart

Setting up the project structure

Navigate into your project directory:

cd shoppingcart

Create a Django App

Create a new app within your project:

python manage.py startapp cart

Adding the app to the project

In shoppingcart/settings.py, add cart to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'cart',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Creating the Shopping Cart App

Create Models

Define your product model in cart/models.py:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='products/', null=True, blank=True)

    def __str__(self):
        return self.name

class Cart(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

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

    def __str__(self):
        return f"{self.quantity} x {self.product.name}"

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

Create Views

Create views for adding items to the cart, viewing the cart, and removing items from the cart in cart/views.py:

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

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

def add_to_cart(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    cart_id = request.session.get('cart_id')
    if not cart_id:
        cart = Cart.objects.create()
        request.session['cart_id'] = cart.id
    else:
        cart = get_object_or_404(Cart, id=cart_id)

    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:cart_detail')

def update_cart_item(request, item_id):
    cart_item = get_object_or_404(CartItem, id=item_id)
    if request.method == 'POST':
        cart_item.quantity = int(request.POST.get('quantity', 1))
        cart_item.save()
    return redirect('cart:cart_detail')

def cart_detail(request):
    cart_id = request.session.get('cart_id')
    if not cart_id:
        return render(request, 'cart_detail.html', {'cart': None, 'total_price': 0})

    cart = get_object_or_404(Cart, id=cart_id)
    total_price = sum(item.total_price() for item in cart.cartitem_set.all())

    return render(request, 'cart_detail.html', {'cart': cart, 'total_price': total_price})

def remove_from_cart(request, product_id):
    cart_id = request.session.get('cart_id')
    cart = get_object_or_404(Cart, id=cart_id)
    cart_item = get_object_or_404(CartItem, cart=cart, product_id=product_id)
    cart_item.delete()
    return redirect('cart:cart_detail')

Add Products in the Admin Interface

To manage products, you can use Django’s admin interface. Ensure you register your models in cart/admin.py:

from django.contrib import admin
from .models import Product, Cart, CartItem

admin.site.register(Product)
admin.site.register(Cart)
admin.site.register(CartItem)

Create Templates

Create templates for displaying products and the cart. In cart/templates, create product_list.html:

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products</title>
    <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
    <div class="container">
        <h1>Products</h1>
        <div class="product-list">
            {% for product in products %}
                <div class="product-item">
                    {% if product.image %}
                        <img src="{{ product.image.url }}" alt="{{ product.name }}">
                    {% else %}
                        <img src="https://via.placeholder.com/150" alt="No Image Available">
                    {% endif %}
                    <h2>{{ product.name }}</h2>
                    <p>Price: ${{ product.price }}</p>
                    <form action="{% url 'cart:add_to_cart' product.id %}" method="post">
                        {% csrf_token %}
                        <button type="submit" class="btn">Add to Cart</button>
                    </form>
                </div>
            {% endfor %}
        </div>
    </div>
</body>
</html>

Create cart_detail.html to display the cart contents:

{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Cart</title>
    <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
    <div class="container">
        <h1>Your Cart</h1>
        {% if cart %}
            {% for item in cart.cartitem_set.all %}
                <div class="cart-item">
                    {% if item.product.image %}
                        <img src="{{ item.product.image.url }}" alt="{{ item.product.name }}">
                    {% else %}
                        <img src="https://via.placeholder.com/50" alt="No Image Available">
                    {% endif %}
                    <div class="details">
                        <p>{{ item.product.name }}</p>
                        <form action="{% url 'cart:update_cart_item' item.id %}" method="post">
                            {% csrf_token %}
                            <input type="number" name="quantity" value="{{ item.quantity }}" min="1" class="quantity-input">
                            <button type="submit" class="update-btn">Update</button>
                        </form>
                    </div>
                    <div class="price">
                        <p>${{ item.total_price }}</p>
                    </div>
                    <div class="remove">
                        <a href="{% url 'cart:remove_from_cart' item.product.id %}" class="btn-remove">Remove</a>
                    </div>
                </div>
            {% endfor %}
            <div class="total-price">
                <p>Total: ${{ total_price }}</p>
            </div>
            <a href="{% url 'cart:product_list' %}" class="btn">Back to Products</a>
        {% else %}
            <p>Your cart is empty.</p>
            <a href="{% url 'cart:product_list' %}" class="btn">Back to Products</a>
        {% endif %}
    </div>
</body>
</html>

Add CSS Styling

Create a CSS file named styles.css in cart/static/ and add the following styles:

body {
    font-family: Arial, sans-serif;
    background-color: #f8f9fa;
    margin: 0;
    padding: 0;
}

.container {
    width: 80%;
    margin: 20px auto;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    font-size: 24px;
    margin-bottom: 20px;
    text-align: center;
}

.product-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.product-item {
    width: 200px;
    margin: 10px;
    padding: 10px;
    background-color: #f1f1f1;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.product-item img {
    width: 100%;
    height: auto;
    border-radius: 8px;
}

.product-item h2 {
    font-size: 18px;
    margin: 10px 0;
}

.product-item p {
    margin: 5px 0;
}

.btn {
    display: inline-block;
    padding: 10px 20px;
    margin: 10px 0;
    background-color: #007bff;
    color: #fff;
    text-decoration: none;
    border-radius: 4px;
    cursor: pointer;
    border: none;
    font-size: 14px;
}

.btn:hover {
    background-color: #0056b3;
}

.cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #ddd;
}

.cart-item img {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 4px;
}

.cart-item .details {
    flex: 1;
    margin-left: 20px;
}

.cart-item .price,
.cart-item .remove {
    width: 100px;
    text-align: right;
}

.cart-item .remove a {
    color: #dc3545;
    text-decoration: none;
}

.cart-item .remove a:hover {
    text-decoration: underline;
}

.total-price {
    text-align: right;
    font-size: 18px;
    font-weight: bold;
    margin: 20px 0;
}


.quantity-input {
    width: 60px;
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-align: center;
    font-size: 14px;
    margin-right: 10px;
}

.update-btn {
    padding: 5px 10px;
    background-color: #28a745;
    color: #fff;
    text-decoration: none;
    border-radius: 4px;
    cursor: pointer;
    border: none;
    font-size: 14px;
}

.update-btn:hover {
    background-color: #218838;
}

Include Static Files

Make sure Django is configured to serve static files in development. Ensure you have these settings in shoppingcart/settings.py:

STATIC_URL = '/static/'

Set Up URL Routing

Add a URL pattern for your view. In cart/urls.py (create this file if it doesn't exist), add:

from django.urls import path
from . import views

app_name = 'cart'

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('add/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
    path('update/<int:item_id>/', views.update_cart_item, name='update_cart_item'),
    path('cart/', views.cart_detail, name='cart_detail'),
    path('remove/<int:product_id>/', views.remove_from_cart, name='remove_from_cart'),
]

Include the app's URLs in your project's URL configuration. Open shoppingcart/urls.py and include the textutils app URLs:

from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include

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

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Run Your Server

Run migrations:

python manage.py makemigrations
python manage.py migrate

Create a superuser to access the admin interface:

python manage.py createsuperuser

Run the development server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/ to see your shopping cart in action.

Full Shopping Cart Project Structure

shoppingcart/
    ├── manage.py
    ├── db.sqlite3
    ├── shoppingcart/
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   ├── asgi.py
    │   └── wsgi.py
    ├── cart/
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── urls.py
    │   ├── views.py
    │   ├── templates/
    │   │       ├── cart_detail.html
    │   │       ├── product_list.html
    │   ├── static/
    │   │       └── styles.css
    │   └── migrations/
    │       └── __init__.py
    ├── products/
    │   ├── Headphones.jpg
    │   ├── Smart_watched.jpg
    │   ├── Programming_Books.jpg

Conclusion

Congratulations! You’ve successfully built a shopping cart using Django. By following this guide, you’ve learned how to set up your project, create models for your cart, and implement the functionality needed to manage products and quantities. This shopping cart can now be integrated into any e-commerce site to enhance user experience and streamline online purchases. Continue exploring Django’s capabilities to add more features and refine your cart. With this foundation, you’re well on your way to creating a powerful online store.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺