E-commerce Website using Tailwind and React using Django
Last Updated :
28 Jun, 2024
Our e-commerce website, "ECOM," aims to offer users a smooth online shopping experience. We use Tailwind CSS for styling, React for interactive user interfaces, and Django for a strong backend. Shopify features a wide range of products across different categories, with functionalities like user authentication, product search, shopping cart management, and secure checkout. Here's how to create this e-commerce website:
Setup Backend (Django):
Step 1: Install Django and create a new project:
pip install django
Backend - 01Step 2: Create a Django Project
django-admin startproject ecommerce_backend
Backend - 02Step 3: Change your directory.
cd ecommerce_backend
Backend - 03Step 4: Use the below command to start your django app.
python manage.py startapp store
Backend - 04Step 5:Install and Set Up React
Navigate to the project directory and create a new React app:
npx create-react-app frontend
FrontEnd - 01cd frontend
FrontEnd - 02Step 6: Integrate Tailwind CSS with React
Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer
Frontend - 03npx tailwindcss init -p
Frontend - 04Step 7: Now its time to add code to your website.
Configure Tailwind by editing tailwind.config.js:
JavaScript
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
Add the following to src/index.css:
CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
Setup the Frontend with React and Tailwind
Creating Components
Step 1: Header Component
JavaScript
import React from 'react';
const Header = () => {
return (
<header className="bg-gray-800 text-white p-4">
<h1 className="text-xl">E-commerce Store</h1>
</header>
);
};
export default Header;
Step 2: Product Listing Component
This component will list all the product available to your database.
JavaScript
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const ProductList = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get('http:127.0.0.1:8000/api/products/')
.then(response => setProducts(response.data))
.catch(error => console.error(error));
}, []);
return (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{products.map(product => (
<div key={product.id} className="border p-4 rounded-lg">
<img src={product.image} alt={product.name} className="h-40 w-full object-cover" />
<h2 className="mt-2 text-lg">{product.name}</h2>
<p className="text-gray-600">${product.price}</p>
</div>
))}
</div>
);
};
export default ProductList;
Add your product and category by adding code in your backend directory.
HTML
//add_category.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Category</title>
{% load static %}
<link href="{% static 'css/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Add Category</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Category</button>
</form>
</div>
</body>
</html>
add_categoryadd_product.html file will help you to add category to your database. Use this template to add category without entering to admin pannel.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Product</title>
{% load static %}
<link href="{% static 'css/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Add Product</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add Product</button>
</form>
</div>
</body>
</html>
add_productNow create 'static' folder to you root directory and create css folder and other folder to store your static files like css file, images, etc.
CSS
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
h1 {
margin-bottom: 20px;
font-size: 24px;
color: #333;
}
form {
display: flex;
flex-direction: column;
}
form .form-field {
margin-bottom: 15px;
}
form .form-field label {
display: block;
margin-bottom: 5px;
color: #555;
}
form .form-field input,
form .form-field select,
form .form-field textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
form button {
padding: 10px;
border: none;
border-radius: 4px;
background: #007bff;
color: #fff;
font-size: 16px;
cursor: pointer;
}
form button:hover {
background: #0056b3;
}
Fetching Data from Django Backend
Step 1: Set Up Django REST Framework
Install Django REST Framework:
pip install djangorestframework
Fetching Data - 01Step 2: Add it to INSTALLED_APPS in settings.py:
Python
INSTALLED_APPS = [
...
'rest_framework',
'products',
]
Step 3: Create API Endpoints
In store/views.py:
Python
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Product
from .serializers import ProductSerializer
from django.shortcuts import render, redirect
from .forms import CategoryForm, ProductForm
@api_view(['GET'])
def product_list(request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
# views.py
def add_category(request):
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save()
return redirect('category_list') # Assuming you have a category list view
else:
form = CategoryForm()
return render(request, 'store/add_category.html', {'form': form})
def add_product(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('product_list') # Assuming you have a product list view
else:
form = ProductForm()
return render(request, 'store/add_product.html', {'form': form})
This file is available inside your products folder. Use products/urls.py to add your urls path.
Python
from django.urls import path
from .views import product_list
urlpatterns = [
path('products/', product_list),
]
In ecommerce_backend/urls.py. This file is the global file for your urls, please add the below code to seprate your app inside the project.
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('products.urls')),
]
This is for your models.py file. Create it and add the below code.
Python
#products/models.py:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
Step 3: Fetch Data in React
Install Axios in React app:
npm install axios
Fetching Data 02Running the Project
Run Django Development Server
python manage.py runserver
Run React Development Server
npm start
Home PageConclusion
By combining Tailwind CSS, React, and Django, you can build a modern, responsive, and scalable e-commerce website. Tailwind simplifies styling, React offers a robust front-end framework, and Django ensures a secure and efficient back end. This stack not only enhances development speed but also provides a maintainable codebase, making it an excellent choice for building e-commerce applications.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read