Below is a step‐by‐step guide to setting up a very basic e-commerce website using Django. This tutorial will walk you through creating a Django project, adding a simple “store” app with a product model, listing products on the homepage, and creating a basic shopping cart view. In a production system, you’d add user authentication, payment processing, security improvements, and more robust error handling, but this example will give you a solid starting point.
1. Set Up Your Django Project
Install Django (if not installed):
bash Copy code
pip install django
Create a new Django project:
bash Copy code
django-admin startproject ecommerce
cd ecommerce
Create a new Django app named “store”:
bash Copy code
python manage.py startapp store
Register the app:
In ecommerce/settings.py, add 'store', to the INSTALLED_APPS list:
python Copy code
INSTALLED_APPS = [
# ...
'store',
]
2. Create Models
In this example, we’ll create a Product model for items and a simple Cart system using sessions.
store/models.py
python Copy code
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ['name']
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('store:product_list_by_category', args=[self.slug])
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['name']
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('store:product_detail', args=[self.id, self.slug])
Note: For a real website, you might expand on these models (adding stock, promotional pricing, etc.).
Make and apply migrations:
bash Copy code
python manage.py makemigrations
python manage.py migrate
3. Create Admin Interfaces
To manage products easily using Django’s admin, register your models:
store/admin.py
python Copy code
from django.contrib import admin
from .models import Category, Product
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'price', 'available', 'created', 'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'available']
prepopulated_fields = {'slug': ('name',)}
Now create a superuser to log into the admin:
bash Copy code
python manage.py createsuperuser
Run the development server:
bash Copy code
python manage.py runserver
Visit http://127.0.0.1:8000/admin/ and add some categories and products.
4. Create Views and URLs
a) Product List & Detail Views
Create views to list all products and to show product details.
store/views.py
python Copy code
from django.shortcuts import render, get_object_or_404
from .models import Category, Product
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
context = {
'category': category,
'categories': categories,
'products': products
}
return render(request, 'store/product/list.html', context)
def product_detail(request, id, slug):
product = get_object_or_404(Product, id=id, slug=slug, available=True)
context = {
'product': product
}
return render(request, 'store/product/detail.html', context)
b) Cart System (Session Based)
For a basic cart, you can create utility functions to add, remove, and clear items. Create a new file:
store/cart.py
python Copy code
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart:
# save an empty cart in the session
cart = self.session['cart'] = {}
self.cart = cart
def add(self, product, quantity=1):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session['cart'] = self.cart
self.session.modified = True
def remove(self, product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def clear(self):
# remove cart from session
del self.session['cart']
self.session.modified = True
def __iter__(self):
product_ids = self.cart.keys()
# Get the product objects and add them to the cart items
from .models import Product
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = float(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(float(item['price']) * item['quantity'] for item in self.cart.values())
c) Cart Views
Add simple views to add to cart and view cart contents.
store/views.py (append these functions)
python Copy code
from django.shortcuts import redirect
from .cart import Cart
def cart_add(request, product_id):
from .models import Product
product = get_object_or_404(Product, id=product_id)
cart = Cart(request)
cart.add(product=product)
return redirect('store:cart_detail')
def cart_remove(request, product_id):
from .models import Product
product = get_object_or_404(Product, id=product_id)
cart = Cart(request)
cart.remove(product)
return redirect('store:cart_detail')
def cart_detail(request):
cart = Cart(request)
return render(request, 'store/cart/detail.html', {'cart': cart})
d) URL Configuration
Create URL patterns for the store app.
store/urls.py
python Copy code
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
# Product list: optional category slug
path('', views.product_list, name='product_list'),
path('category/<slug:category_slug>/', views.product_list, name='product_list_by_category'),
# Detailed view for a product
path('product/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
# Cart URLs
path('cart/', views.cart_detail, name='cart_detail'),
path('cart/add/<int:product_id>/', views.cart_add, name='cart_add'),
path('cart/remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
]
Next, include the store URLs in your main project’s URL configuration.
ecommerce/urls.py
python Copy code
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
]
5. Create Templates
Create a folder structure for your templates inside the store app. For example:
code Copy code
store/
├── templates/
│ └── store/
│ ├── base.html
│ ├── product/
│ │ ├── list.html
│ │ └── detail.html
│ └── cart/
│ └── detail.html
a) Base Template
store/templates/store/base.html
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>E-commerce Site</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
<div class="container">
<a class="navbar-brand" href="{% url 'store:product_list' %}">E-commerce Site</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav me-auto">
{% for category in categories %}
<li class="nav-item">
<a class="nav-link" href="{{ category.get_absolute_url }}">{{ category.name }}</a>
</li>
{% endfor %}
</ul>
<a class="btn btn-outline-secondary" href="{% url 'store:cart_detail' %}">
Cart ({{ request.session.cart|length if request.session.cart else 0 }})
</a>
</div>
</div>
</nav>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
Tip: In your view functions (like product_list), make sure to pass categories into the context if you want them available in the base template. Alternatively, you can use a context processor to ensure categories are always available.
b) Product List Template
store/templates/store/product/list.html
html Copy code
{% extends "store/base.html" %}
{% block content %}
<h1>Products {% if category %} in {{ category.name }}{% endif %}</h1>
<div class="row">
{% for product in products %}
<div class="col-md-4 mb-4">
<div class="card">
{% if product.image %}
<img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.name }}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">${{ product.price }}</p>
<a href="{{ product.get_absolute_url }}" class="btn btn-primary">View Details</a>
<a href="{% url 'store:cart_add' product.id %}" class="btn btn-success">Add to Cart</a>
</div>
</div>
</div>
{% empty %}
<p>No products available.</p>
{% endfor %}
</div>
{% endblock %}
c) Product Detail Template
store/templates/store/product/detail.html
html Copy code
{% extends "store/base.html" %}
{% block content %}
<div class="row">
<div class="col-md-6">
{% if product.image %}
<img src="{{ product.image.url }}" class="img-fluid" alt="{{ product.name }}">
{% endif %}
</div>
<div class="col-md-6">
<h2>{{ product.name }}</h2>
<p>${{ product.price }}</p>
<p>{{ product.description }}</p>
<a href="{% url 'store:cart_add' product.id %}" class="btn btn-success">Add to Cart</a>
</div>
</div>
{% endblock %}
d) Cart Detail Template
store/templates/store/cart/detail.html
html Copy code
{% extends "store/base.html" %}
{% block content %}
<h2>Your Shopping Cart</h2>
{% if cart|length > 0 %}
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for item in cart %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.price|floatformat:2 }}</td>
<td>${{ item.total_price|floatformat:2 }}</td>
<td>
<a class="btn btn-danger btn-sm" href="{% url 'store:cart_remove' item.product.id %}">Remove</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h4>Total: ${{ cart.get_total_price|floatformat:2 }}</h4>
<!-- Future improvement: Add checkout button -->
{% else %}
<p>Your cart is empty.</p>
{% endif %}
{% endblock %}
6. Running and Testing
Collect Static Files (if needed):
For development, Django can serve static files. In production, you’d need to configure a static files server.
Run the Development Server:
bash Copy code
python manage.py runserver
Test in Your Browser:
7. Next Steps
This basic setup can be further enhanced by:
Implementing user authentication and associating a persistent cart with a user.
Integrating payment gateways (e.g., Stripe, PayPal).
Adding order processing and email notifications.
Improving error handling, security, and performance.
Using Django’s class-based views and generic views for cleaner code.
By following this guide, you now have a foundational Django e-commerce site that you can expand and customize according to your project requirements.
Happy coding!