Django E-commerce Site in Python
About the project: Creating a robust e-commerce site with Django requires several interconnected files and folders. Since we only generate the content of the files here, We'll provide the essential Python and HTML files needed for a minimal, runnable foundation of a product listing page. This project will be named ecommerce_project and contain a single app called store.
Project Level: AdvanceBefore running, you will need to:
- Install Django: pip install django
- Create the project structure manually, placing the files in the correct folders.
- Run migrations: python manage.py makemigrations store and then python manage.py migrate
- Create a superuser to add products: python manage.py createsuperuser
- Run the server: python manage.py runserver
Project Configuration (ecommerce_project/settings.py)
This file contains the main configuration for the Django project, including database settings, installed apps, and template directories.
"""
Django settings for ecommerce_project.
Generated by 'django-admin startproject' using Django 5.0.6.
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@e^i96n%_o1=s1^m)a-5z38^r*t%_73m8=^a*+9d9j$d*t_1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# Required Django Apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Custom Apps
'store.apps.StoreConfig', # Your e-commerce app
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ecommerce_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# Look for templates inside each app's 'templates' directory
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ecommerce_project.wsgi.application'
# Database
# Using SQLite database for simplicity in this minimal project
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Project Routing (ecommerce_project/urls.py)
This file routes URLs from the root of the project to the respective application's urls.py file.
"""
URL configuration for ecommerce_project.
The `urlpatterns` list routes URLs to views.
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# Admin site is accessible at /admin/
path('admin/', admin.site.urls),
# All paths starting with the root ('') are sent to the 'store' app for processing
path('', include('store.urls')),
]
Store App Model (store/models.py)
This defines the database structure for our products.
from django.db import models
from django.urls import reverse
class Product(models.Model):
"""
Represents a product in the e-commerce store.
"""
name = models.CharField(max_length=200, db_index=True, help_text="The name of the product.")
slug = models.SlugField(max_length=200, unique=True, help_text="A unique slug for the product URL.")
description = models.TextField(blank=True, help_text="A detailed description of the product.")
price = models.DecimalField(max_digits=10, decimal_places=2, help_text="The price of the product.")
stock = models.PositiveIntegerField(help_text="Current stock level.")
available = models.BooleanField(default=True, help_text="Is the product currently available for purchase?")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
"""Returns the string representation of the product."""
return self.name
# Optional: Define how to get the URL for a single product (used for detail view later)
# def get_absolute_url(self):
# return reverse('store:product_detail', args=[self.id, self.slug])
Store App Views (store/views.py)
This file contains the logic for rendering the product list page.
from django.shortcuts import render
from .models import Product
def product_list(request):
"""
Displays a list of all available products.
"""
# Query all products that are marked as available
products = Product.objects.filter(available=True)
# Prepare the context to be passed to the template
context = {
'products': products,
'title': 'Welcome to the Django Store',
}
# Render the product_list.html template with the product data
return render(request, 'store/product_list.html', context)
Store App Routing (store/urls.py)
This file handles URL routing specifically for the store application.
from django.urls import path
from . import views
# Define the app name for URL reversing (e.g., in templates)
app_name = 'store'
urlpatterns = [
# path('', views.product_list, name='product_list') maps the root of the app ('/')
# to the product_list view function.
path('', views.product_list, name='product_list'),
# Future paths would go here, e.g., product detail:
# path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
]
HTML Templates
We need a base template for layout and a specific template for the product list. Place these files inside the directory store/templates/store/.
Base Template
(store/templates/store/base.html)This sets up the basic HTML structure, including a header and a place where specific page content will be injected.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Django E-commerce{% endblock %}</title>
<style>
body { font-family: sans-serif; background-color: #f7f7f7; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.header { background-color: #3f51b5; color: white; padding: 15px 20px; text-align: center; }
.header a { color: white; text-decoration: none; font-weight: bold; }
.product-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; }
.product-card { background: white; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 20px; transition: transform 0.2s; }
.product-card:hover { transform: translateY(-5px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); }
.price { color: #f44336; font-size: 1.25rem; font-weight: bold; margin-top: 10px; }
.btn-primary { background-color: #4CAF50; color: white; padding: 10px 15px; border-radius: 4px; display: inline-block; text-decoration: none; margin-top: 15px; }
</style>
</head>
<body>
<header class="header">
<div class="container">
<a href="{% url 'store:product_list' %}"><h1>E-Commerce Django Shop</h1></a>
</div>
</header>
<main class="container">
{% block content %}
{% endblock %}
</main>
<footer class="text-center" style="padding: 20px; color: #666; font-size: 0.8rem;">
© 2024 Django Shop. All rights reserved.
</footer>
</body>
</html>
Product List Template
(store/templates/store/product_list.html)This template iterates over the products passed from the view and renders them as cards.
{% extends 'store/base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h2 style="font-size: 2rem; margin-bottom: 20px; color: #333;">Featured Products</h2>
{% if products %}
<div class="product-grid">
{% for product in products %}
<div class="product-card">
<h3 style="font-size: 1.5rem; color: #3f51b5; margin-bottom: 5px;">{{ product.name }}</h3>
<p style="color: #666;">{{ product.description|truncatechars:100 }}</p>
<div style="height: 150px; background-color: #eee; border-radius: 4px; margin: 15px 0; display: flex; align-items: center; justify-content: center; color: #999;">
[Image Placeholder]
</div>
<div class="price">${{ product.price }}</div>
{% if product.stock > 0 %}
<p style="color: green; font-size: 0.9rem;">In Stock ({{ product.stock }})</p>
<a href="#" class="btn-primary">Add to Cart</a>
{% else %}
<p style="color: red; font-size: 0.9rem;">Out of Stock</p>
{% endif %}
</div>
{% endfor %}
</div>
{% else %}
<p style="text-align: center; color: #999; padding: 40px;">No products are currently available in the shop.</p>
{% endif %}
{% endblock %}
This collection of files gives you the basic model, view, and template (MVT) structure of a Django e-commerce application.
To get started, make sure to follow the setup steps outlined at the beginning (install Django, create the file structure, run migrations, and start the server).
You can add more if you would like to dive deeper into adding features like User Authentication, a functional Shopping Cart model, or setting up the Admin interface to manage your products!
Project Structure
This project consists of a multiple Python scripts. You can name create these files as given.
Copy the above code into your respective files. The code is well-commented to help you understand each part of the files.
← Back to Projects