Comprehensive Guide
Setting Up
an Online Shopping Cart Project with Django
Steps to Set Up the
Online Shopping Cart Project with Django
These are steps to guide on how to set up and develop the Online Shopping Cart project using Python and Django.
Step 1: Install Python
and Django
1.
Install Python:
o Download
and install the latest version of Python from the official website.
o After
installation, ensure that Python is added to the system PATH.
o You
can verify the installation by running the following command in your terminal:
python --version
2.
Install Django:
o Install
Django using pip, Python's package manager.
pip install django
o To
verify the installation, run:
django-admin --version
Step 2: Create a Django
Project
1.
Create a Project Directory:
o Navigate
to the folder where you want to store your project, and then create a new
directory.
mkdir online_shopping_cart
cd online_shopping_cart
2.
Start a Django Project:
o Initialize
a new Django project using the command:
django-admin startproject online_shopping_cart .
This will create a new
Django project with the necessary files (settings.py, urls.py, etc.).
3.
Run the Development Server:
o Start
the development server to verify if the Django project is set up correctly:
python manage.py runserver
o Open
your browser and go to http://127.0.0.1:8000/ to see the default Django welcome
page.
Step 3: Set Up the
Database
Django uses SQLite by default,
but you can switch to another database like PostgreSQL or MySQL.
1.
Configure Database:
o Open
the settings.py file of the Django project and find the DATABASES setting. By
default, it's set to SQLite.
§ If you're using SQLite (default):
'default':
{ 'ENGINE':
'django.db.backends.sqlite3', 'NAME':
BASE_DIR / 'db.sqlite3', } } |
§ If
you're using PostgreSQL or MySQL, update the ENGINE, NAME, USER, PASSWORD, and
other parameters accordingly.
If you're using MySQL as
your database, replace the DATABASES configuration in your settings.py file
with the following:
DATABASES = { 'default':
{ 'ENGINE':
'django.db.backends.mysql', 'NAME':
'your_database_name', # Replace with your database name 'USER':
'your_database_user', # Replace with your MySQL username 'PASSWORD':
'your_password', # Replace with your MySQL password 'HOST':
'localhost', # Replace with your MySQL host (default is
'localhost') 'PORT':
'3306', # Replace with your MySQL port (default is '3306') } } |
Additional Steps:
1.
Install MySQL Client:
Ensure you have the MySQL client installed by running:
pip install mysqlclient
If you encounter issues
with mysqlclient, you can use PyMySQL as an alternative:
pip install pymysql
Then, in your __init__.py
file of the project, add the following:
import pymysql
pymysql.install_as_MySQLdb()
2.
Create the Database:
Before running migrations, create the database in MySQL using:
CREATE DATABASE your_database_name;
2.
Apply Migrations:
o Run
the initial migrations to set up the database tables for Django:
python manage.py migrate
Step 4: Create Django
Apps
We will create four
primary Django apps for handling different features:
- Users
(for user authentication)
- Products
(for displaying and managing products)
- Cart
(for cart management)
- Orders
(for managing orders)
1.
Create the Apps:
o Use
the following commands to create each app:
python
manage.py startapp users python
manage.py startapp products python
manage.py startapp cart python
manage.py startapp orders |
2.
Register Apps in settings.py:
o Add
each app to the INSTALLED_APPS list in settings.py:
INSTALLED_APPS
= [ ... 'users', 'products', 'cart', 'orders', ] |
Step 5: Define Models for Each App
1.
User Model (users/models.py):
o Define
the user model (you can extend the default User model or create a custom one if
needed).
o Example:
from
django.contrib.auth.models import AbstractUser class
CustomUser(AbstractUser): address
= models.CharField(max_length=255) |
2.
Product Model (products/models.py):
o Define
the Product model with fields like name, description, price, and image.
o Example:
from
django.db import models class
Product(models.Model): name
= models.CharField(max_length=255) description
= models.TextField() price
= models.DecimalField(max_digits=10, decimal_places=2) image
= models.ImageField(upload_to='products/')
def __str__(self): return
self.name |
3.
Cart Model (cart/models.py):
o Define
models for the cart and cart items. For example, a cart item will belong to a
specific product and user.
o Example:
from
django.db import models from
products.models import Product from
users.models import CustomUser class
Cart(models.Model): user
= models.ForeignKey(CustomUser, on_delete=models.CASCADE) products
= models.ManyToManyField(Product, through='CartItem') class
CartItem(models.Model): cart
= models.ForeignKey(Cart, on_delete=models.CASCADE) product
= models.ForeignKey(Product, on_delete=models.CASCADE) quantity
= models.IntegerField() |
4.
Order Model (orders/models.py):
o Define
the Order and OrderItem models to store order information and items.
o Example:
from
django.db import models from
products.models import Product from
users.models import CustomUser class
Order(models.Model): user
= models.ForeignKey(CustomUser, on_delete=models.CASCADE) total_amount
= models.DecimalField(max_digits=10, decimal_places=2) status
= models.CharField(max_length=255) class
OrderItem(models.Model): order
= models.ForeignKey(Order, on_delete=models.CASCADE) product
= models.ForeignKey(Product, on_delete=models.CASCADE) quantity
= models.IntegerField() |
Step 6: Create Admin Interfaces
1.
Register Models in Admin (admin.py):
o Register
the models for each app in the admin.py file to manage them via Django’s admin
interface.
o Example
for products/admin.py:
from
django.contrib import admin from .models
import Product admin.site.register(Product) |
2.
Create Admin Users:
o Create
a superuser for accessing the Django admin:
python manage.py createsuperuser
Step 7: Create Views and Templates
1.
Views:
o Create
views in each app to handle logic for displaying products, managing the cart,
processing orders, and handling user registration/login.
o Example
view for displaying products in products/views.py:
from
django.shortcuts import render from .models
import Product def
product_list(request): products
= Product.objects.all() return
render(request, 'products/product_list.html', {'products': products}) |
2.
Templates:
o Create
the HTML templates for each page. For example, a template for displaying
products (product_list.html).
{% for
product in products %} <div
class="product"> <img
src="{{ product.image.url }}" alt="{{ product.name
}}"> <h2>{{
product.name }}</h2> <p>{{
product.description }}</p> <p>${{
product.price }}</p> <a
href="{% url 'add_to_cart' product.id %}">Add to Cart</a> </div> {% endfor %} |
3.
URL Routing:
o Set
up URL patterns to route requests to the appropriate views. For example, add
URL patterns in products/urls.py:
from
django.urls import path from . import
views urlpatterns =
[ path('',
views.product_list, name='product_list'), ] |
Step 8: Set Up Cart and Checkout
1.
Cart Views:
o Create
views for adding/removing products from the cart, viewing the cart, and
proceeding to checkout.
2.
Checkout and Payment Integration:
o Set
up the checkout process, where users can enter shipping information and select
a payment method.
o Integrate
with a payment gateway like Stripe or PayPal to process payments
securely.
Step 9: Testing
- Test
each part of the application:
- User
registration and login.
- Product
listing and cart functionality.
- Order
creation and payment processing.
Step 10: Deploy the Project
1.
Set Up Static and Media Files:
o Ensure
static and media files are served correctly in production by configuring
STATIC_URL, MEDIA_URL, and the corresponding directories in settings.py.
2.
Deploy to a Hosting Platform:
o Deploy
your Django app to a hosting platform like Heroku, DigitalOcean,
or AWS. Make sure to configure the database, environment variables, and
static files for production.
Conclusion
By following these steps,
you will have set up a basic Django-based Online Shopping Cart with features
like product browsing, cart management, order creation, and payment processing.
You can then expand the functionality further by adding features like user
reviews, advanced search, promotions, and more.
FOR Code ...Click Here