Comprehensive Guide to Building an E-commerce Website with Django
Creating an e-commerce website is an excellent way to provide a platform for your friend's boutique store. Django, a high-level Python web framework, is well-suited for this task due to its scalability, security features, and rich ecosystem. This guide will walk you through building a fully functional e-commerce website using Django, including setting up the project, designing models, creating views and templates, managing user authentication, and styling the frontend with HTML and CSS.
Table of Contents
- Prerequisites
- Project Setup
- Designing the Models
- Admin Interface
- Creating Views and Templates
- URL Configuration
- Static Files and Media
- Running and Testing the Project
- Conclusion
Prerequisites
Before you begin, ensure you have the following installed on your machine:
- Python 3.x: Django is a Python framework, so Python is essential.
- pip: Python's package installer.
- Virtual Environment Tool:
venv (comes with Python 3.3+) or virtualenv.
- Git (optional): For version control.
- Code Editor: Such as VS Code, PyCharm, or Sublime Text.
Project Setup
1. Install Python and Django
Ensure Python is installed by running:
python3 --version
If Python isn't installed, download it from the official website and follow the installation instructions.
Install Django using pip:
pip install django
Verify the installation:
django-admin --version
2. Create a Virtual Environment
It's best practice to use a virtual environment to manage project-specific dependencies.
Create and activate a virtual environment:
# Create a virtual environment named 'env'
python3 -m venv env
# Activate the virtual environment on Unix or MacOS
source env/bin/activate
# Activate on Windows
env\Scripts\activate
Your command prompt should now indicate that the virtual environment is active.
3. Start a Django Project and App
Create a new Django project named boutique_store:
django-admin startproject boutique_store
cd boutique_store
Inside the project, create an app named store:
python manage.py startapp store
Your project structure should look like this:
boutique_store/
manage.py
boutique_store/
__init__.py
settings.py
urls.py
wsgi.py
store/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
Add the store app to INSTALLED_APPS in boutique_store/settings.py:
# boutique_store/settings.py
INSTALLED_APPS = [
# ...
'store',
# ...
]
Designing the Models
Models define the structure of your database. We'll create models for categories, products, carts, cart items, orders, and order items.
1. Category Model
Represents product categories.
# store/models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
class Meta:
verbose_name_plural = 'Categories'
ordering = ['name']
def __str__(self):
return self.name
- Fields:
name: The name of the category.
slug: URL-friendly representation of the name.
2. Product Model
Represents products in the store.
# store/models.py
from django.db import models
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='products/')
stock = models.PositiveIntegerField(default=0)
available = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
- Fields:
category: Foreign key linking to Category.
name, slug, description, price: Product details.
image: Image of the product.
stock: Quantity available.
available: Availability status.
- Timestamps for creation and updates.
3. Cart and CartItem Models
Manage user shopping carts.
# store/models.py
from django.contrib.auth.models import User
class Cart(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Cart of {self.user.username}"
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)
class Meta:
unique_together = ('cart', 'product')
def __str__(self):
return f"{self.quantity} of {self.product.name}"
def get_total_price(self):
return self.quantity * self.product.price
-
Cart:
- Linked to a
User.
- Contains cart items.
-
CartItem:
- Linked to
Cart and Product.
- Tracks quantity of each product.
4. Order and OrderItem Models
Handle order processing.
# store/models.py
class Order(models.Model):
user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE)
ordered_at = models.DateTimeField(auto_now_add=True)
address = models.CharField(max_length=255)
paid = models.BooleanField(default=False)
def __str__(self):
return f"Order {self.id} by {self.user.username}"
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.product.name}"
def get_cost(self):
return self.price * self.quantity
-
Order:
- Linked to a
User.
- Contains order details like address and payment status.
-
OrderItem:
- Linked to
Order and Product.
- Tracks individual items in an order.
Admin Interface
Django's admin interface allows you to manage your models easily.
# store/admin.py
from django.contrib import admin
from .models import Category, Product, Cart, CartItem, Order, OrderItem
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
list_display = ['name']
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'category', 'price', 'available', 'stock']
list_filter = ['available', 'category']
list_editable = ['price', 'available', 'stock']
prepopulated_fields = {'slug': ('name',)}
@admin.register(Cart)
class CartAdmin(admin.ModelAdmin):
list_display = ['user', 'created_at']
@admin.register(CartItem)
class CartItemAdmin(admin.ModelAdmin):
list_display = ['cart', 'product', 'quantity']
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['id', 'user', 'ordered_at', 'paid']
list_filter = ['paid', 'ordered_at']
search_fields = ['user__username', 'id']
@admin.register(OrderItem)
class OrderItemAdmin(admin.ModelAdmin):
list_display = ['order', 'product', 'price', 'quantity']
Explanation:
@admin.register: Decorator to register models with the admin site.
prepopulated_fields: Automatically populates the slug field based on name.
list_display, list_filter, list_editable: Customize admin list views for better usability.
Apply Migrations and Create Superuser:
# Make migrations for the store app
python manage.py makemigrations store
# Apply migrations
python manage.py migrate
# Create a superuser to access the admin
python manage.py createsuperuser
Creating Views and Templates
We'll create views to handle HTTP requests and templates to render HTML pages.
1. Home Page
Displays featured products and categories.
# store/views.py
from django.shortcuts import render
from .models import Category, Product
def home(request):
categories = Category.objects.all()
products = Product.objects.filter(available=True)[:10] # Display first 10 products
context = {
'categories': categories,
'products': products
}
return render(request, 'store/home.html', context)
Template: store/templates/store/home.html
<!DOCTYPE html>
<html>
<head>
<title>Boutique Store - Home</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Welcome to the Boutique Store</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
<section>
<h2>Categories</h2>
<ul>
{% for category in categories %}
<li><a href="{% url 'product_list_by_category' category.slug %}">{{ category.name }}</a></li>
{% endfor %}
</ul>
</section>
<section>
<h2>Featured Products</h2>
<ul class="product-list">
{% for product in products %}
<li>
<a href="{% url 'product_detail' product.slug %}">
<img src="{{ product.image.url }}" alt="{{ product.name }}">
<h3>{{ product.name }}</h3>
<p>${{ product.price }}</p>
</a>
</li>
{% endfor %}
</ul>
</section>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
- Header: Contains navigation links. Shows
Login and Register for unauthenticated users and Logout for authenticated users.
- Main:
- Categories Section: Lists all product categories with links.
- Featured Products Section: Displays a list of available products with images, names, and prices.
- Footer: Simple footer with copyright.
2. Product Listing
Displays all products or products within a specific category.
# store/views.py
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)
Template: store/templates/store/product_list.html
<!DOCTYPE html>
<html>
<head>
<title>Boutique Store - Products</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Products</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">All Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
<aside>
<h2>Categories</h2>
<ul>
{% for category in categories %}
<li>
<a href="{% url 'product_list_by_category' category.slug %}">{{ category.name }}</a>
</li>
{% endfor %}
</ul>
</aside>
<section>
<h2>{% if category %}{{ category.name }}{% else %}All Products{% endif %}</h2>
<ul class="product-list">
{% for product in products %}
<li>
<a href="{% url 'product_detail' product.slug %}">
<img src="{{ product.image.url }}" alt="{{ product.name }}">
<h3>{{ product.name }}</h3>
<p>${{ product.price }}</p>
</a>
</li>
{% endfor %}
</ul>
</section>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
- Aside: Sidebar listing all categories for filtering.
- Section: Displays products, optionally filtered by category.
3. Product Detail Page
Displays detailed information about a single product and allows adding it to the cart.
# store/views.py
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, available=True)
context = {
'product': product
}
return render(request, 'store/product_detail.html', context)
Template: store/templates/store/product_detail.html
<!DOCTYPE html>
<html>
<head>
<title>{{ product.name }} - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>{{ product.name }}</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
<div class="product-detail">
<img src="{{ product.image.url }}" alt="{{ product.name }}">
<div class="product-info">
<h2>${{ product.price }}</h2>
<p>{{ product.description }}</p>
<form action="{% url 'add_to_cart' product.id %}" method="POST">
{% csrf_token %}
<label for="quantity">Quantity:</label>
<input type="number" name="quantity" id="quantity" value="1" min="1">
<button type="submit">Add to Cart</button>
</form>
</div>
</div>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
- Product Detail: Shows a larger image, detailed description, price, and a form to add the product to the cart with a specified quantity.
4. Shopping Cart
Displays items added to the cart and allows users to modify quantities or remove items.
# store/views.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.urls import reverse
@login_required
def cart_view(request):
cart, created = Cart.objects.get_or_create(user=request.user)
items = cart.items.all()
total = sum(item.get_total_price() for item in items)
context = {
'cart': cart,
'items': items,
'total': total
}
return render(request, 'store/cart.html', context)
@login_required
def add_to_cart(request, product_id):
cart, created = Cart.objects.get_or_create(user=request.user)
product = get_object_or_404(Product, id=product_id, available=True)
quantity = int(request.POST.get('quantity', 1))
cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)
if not created:
cart_item.quantity += quantity
cart_item.save()
return HttpResponseRedirect(reverse('cart'))
@login_required
def remove_from_cart(request, item_id):
cart = get_object_or_404(Cart, user=request.user)
item = get_object_or_404(CartItem, id=item_id, cart=cart)
item.delete()
return HttpResponseRedirect(reverse('cart'))
Template: store/templates/store/cart.html
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Your Cart</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
{% if items %}
<table>
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.product.price }}</td>
<td>${{ item.get_total_price }}</td>
<td>
<form action="{% url 'remove_from_cart' item.id %}" method="POST">
{% csrf_token %}
<button type="submit">Remove</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h3>Total: ${{ total }}</h3>
<a href="{% url 'checkout' %}">Proceed to Checkout</a>
{% else %}
<p>Your cart is empty.</p>
{% endif %}
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
- Table: Lists all items in the cart with options to remove them.
- Total: Displays the total cost of items in the cart.
- Proceed to Checkout: Link to the checkout page.
5. Checkout
Allows users to enter shipping information and place an order.
# store/views.py
from django import forms
class CheckoutForm(forms.Form):
address = forms.CharField(max_length=255, widget=forms.Textarea(attrs={'rows':3}))
@login_required
def checkout(request):
cart = get_object_or_404(Cart, user=request.user)
items = cart.items.all()
if not items:
return HttpResponseRedirect(reverse('cart'))
if request.method == 'POST':
form = CheckoutForm(request.POST)
if form.is_valid():
order = Order.objects.create(
user=request.user,
address=form.cleaned_data['address'],
paid=False,
)
for item in items:
OrderItem.objects.create(
order=order,
product=item.product,
price=item.product.price,
quantity=item.quantity
)
# Optionally, decrease stock
item.product.stock -= item.quantity
item.product.save()
# Clear the cart
cart.items.all().delete()
# Redirect to a success page or order detail
return render(request, 'store/checkout_success.html', {'order': order})
else:
form = CheckoutForm()
total = sum(item.get_total_price() for item in items)
context = {
'form': form,
'items': items,
'total': total
}
return render(request, 'store/checkout.html', context)
Template: store/templates/store/checkout.html
<!DOCTYPE html>
<html>
<head>
<title>Checkout - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Checkout</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
<h2>Order Summary</h2>
<ul>
{% for item in items %}
<li>{{ item.quantity }} x {{ item.product.name }} - ${{ item.get_total_price }}</li>
{% endfor %}
</ul>
<h3>Total: ${{ total }}</h3>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Place Order</button>
</form>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Template: store/templates/store/checkout_success.html
<!DOCTYPE html>
<html>
<head>
<title>Order Successful - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Thank You for Your Order!</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
{% if user.is_authenticated %}
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
<a href="{% url 'register' %}">Register</a>
{% endif %}
</nav>
</header>
<main>
<p>Your order #{{ order.id }} has been placed successfully.</p>
<p>We will notify you once the order is shipped.</p>
<a href="{% url 'home' %}">Continue Shopping</a>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
- Checkout Form: Users enter their shipping address.
- Order Processing:
- Creates an
Order and associated OrderItems.
- Optionally decreases product stock.
- Clears the user's cart.
- Displays a success message with order details.
6. User Authentication (Register, Login, Logout)
Implement user registration, login, and logout functionalities.
# store/views.py
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
def register_view(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
# Create a cart for the new user
Cart.objects.create(user=user)
login(request, user)
return HttpResponseRedirect(reverse('home'))
else:
form = UserCreationForm()
return render(request, 'store/register.html', {'form': form})
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
return HttpResponseRedirect(reverse('home'))
else:
form = AuthenticationForm()
return render(request, 'store/login.html', {'form': form})
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('home'))
Templates:
-
Register: store/templates/store/register.html
<!DOCTYPE html>
<html>
<head>
<title>Register - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Register</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
<a href="{% url 'login' %}">Login</a>
</nav>
</header>
<main>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
-
Login: store/templates/store/login.html
<!DOCTYPE html>
<html>
<head>
<title>Login - Boutique Store</title>
<link rel="stylesheet" href="{% static 'store/css/styles.css' %}">
</head>
<body>
<header>
<h1>Login</h1>
<nav>
<a href="{% url 'home' %}">Home</a>
<a href="{% url 'product_list' %}">Products</a>
<a href="{% url 'cart' %}">Cart</a>
<a href="{% url 'register' %}">Register</a>
</nav>
</header>
<main>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
</main>
<footer>
<p>© 2023 Boutique Store</p>
</footer>
</body>
</html>
Explanation:
-
Registration:
- Users can create a new account.
- Upon successful registration, a cart is created for the user, and they are logged in automatically.
-
Login:
- Authenticates existing users.
-
Logout:
- Logs out the user and redirects to the home page.
URL Configuration
Map URLs to their corresponding views.
# boutique_store/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls')),
]
# Serve media files during development
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Create store/urls.py:
# store/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('products/', views.product_list, name='product_list'),
path('products/category/<slug:category_slug>/', views.product_list, name='product_list_by_category'),
path('product/<slug:slug>/', views.product_detail, name='product_detail'),
path('cart/', views.cart_view, name='cart'),
path('cart/add/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
path('cart/remove/<int:item_id>/', views.remove_from_cart, name='remove_from_cart'),
path('checkout/', views.checkout, name='checkout'),
path('register/', views.register_view, name='register'),
path('login/', views.login_view, name='login'),
path('logout/', views.logout_view, name='logout'),
]
Explanation:
- Each URL pattern is associated with a view function.
- Names like
'home', 'product_list' are used for URL reversing in templates.
Static Files and Media
Manage static assets (CSS, JavaScript) and user-uploaded media (product images).
1. Configuring Static Files
In settings.py, add the following configurations:
# boutique_store/settings.py
import os
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
# Media files (Uploaded images)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Explanation:
- STATIC_URL: URL to access static files.
- STATICFILES_DIRS: Directories where Django will look for static files.
- MEDIA_URL: URL to access media files.
- MEDIA_ROOT: Directory where uploaded media files are stored.
2. Creating CSS Styles
Create a directory for static files: static/store/css/.
Example: static/store/css/styles.css
/* styles.css */
/* General Styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
/* Header */
header {
background-color: #333;
color: #fff;
padding: 15px 20px;
}
header h1 {
margin: 0;
display: inline-block;
}
nav {
display: inline-block;
margin-left: 50px;
}
nav a {
color: #fff;
margin-right: 15px;
text-decoration: none;
}
nav a:hover {
text-decoration: underline;
}
/* Main Content */
main {
padding: 20px;
}
/* Product List */
.product-list {
list-style-type: none;
padding: 0;
display: flex;
flex-wrap: wrap;
}
.product-list li {
border: 1px solid #ddd;
border-radius: 5px;
margin: 10px;
padding: 10px;
width: 200px;
text-align: center;
}
.product-list img {
width: 100%;
height: 200px;
object-fit: cover;
}
.product-detail {
display: flex;
gap: 20px;
}
.product-detail img {
width: 300px;
height: 300px;
object-fit: cover;
}
.product-info {
max-width: 600px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 10px;
text-align: left;
}
button {
padding: 5px 10px;
cursor: pointer;
background-color: #333;
color: #fff;
border: none;
border-radius: 3px;
}
button:hover {
background-color: #555;
}
/* Footer */
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 10px;
position: fixed;
bottom: 0;
width: 100%;
}
Explanation:
- Layout Styles: Define styling for headers, navigation, main content, and footers.
- Product List: Styles product listings with images and descriptions.
- Product Detail: Layout for detailed product information.
- Forms and Tables: Styles for forms and tables used in the cart and checkout pages.
Running and Testing the Project
-
Ensure All Dependencies Are Installed:
-
Apply Migrations:
python manage.py makemigrations
python manage.py migrate
-
Create a Superuser:
python manage.py createsuperuser
-
Start the Development Server:
python manage.py runserver
-
Access the Website:
- Open your browser and navigate to
http://127.0.0.1:8000/ to view the home page.
- Access the admin interface at
http://127.0.0.1:8000/admin/ to add categories and products.
-
Adding Products:
- Log in to the admin site using the superuser credentials.
- Add Categories first.
- Then add Products, ensuring to upload images. Uploaded images will be stored in the
media/products/ directory.
-
Testing Functionality:
- Registration: Register a new user.
- Login: Log in with the newly created account.
- Browse Products: Navigate through categories and view product details.
- Add to Cart: Add products to the cart.
- View Cart: Review items in the cart.
- Checkout: Proceed to checkout and place an order.
- Order Confirmation: Receive a success message upon order placement.
Conclusion
Congratulations! You've successfully built a basic e-commerce website using Django. This platform allows users to browse products, add them to a shopping cart, and place orders. Administrators can manage products, categories, and orders through Django's admin interface.
Next Steps:
-
Enhancements:
- Search Functionality: Implement search to allow users to find products quickly.
- Pagination: Add pagination to product listings for better navigation.
- User Profiles: Expand user profiles to include order history and preferences.
- Payment Integration: Integrate payment gateways like Stripe or PayPal for processing payments.
- Email Notifications: Set up email confirmations for orders and account activities.
- Responsive Design: Improve CSS to ensure the website is mobile-friendly.
-
Security:
- HTTPS: Secure the website with SSL certificates.
- Input Validation: Ensure all forms have proper validation to prevent malicious data.
-
Deployment:
- Deploy the website to a production server using platforms like Heroku, AWS, or DigitalOcean.
- Configure static and media files for production.
- Set up a proper database (like PostgreSQL) for better performance and scalability.
-
Performance Optimization:
- Implement caching strategies.
- Optimize images and static assets for faster loading times.
-
Advanced Features:
- Inventory Management: Advanced stock tracking and notifications for low inventory.
- Review System: Allow users to leave reviews and ratings for products.
- Wishlist: Enable users to save products for future purchases.
- Discounts and Coupons: Implement discount codes and promotional offers.
Building an e-commerce platform is an iterative process. Continuously gather feedback, monitor performance, and make improvements to provide the best experience for both administrators and customers.
Good luck with your project, and may your friend's boutique store thrive online!