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
Create an Agency Website using React and Tailwind
An agency website using React and Tailwind consists of basic components such as a home page, services, contact us, features, etc. It also has a contact form that will enable the user to contact if any issue arises on the website or the benefits to be availed by the user through the website. Preview
7 min read
E-commerce Website using Django
This project deals with developing a Virtual website âE-commerce Websiteâ. It provides the user with a list of the various products available for purchase in the store. For the convenience of online shopping, a shopping cart is provided to the user. After the selection of the goods, it is sent for t
11 min read
Create A Real Estate Website Using React and Tailwind CSS
A Real Estate Website built with React JS and Tailwind CSS is a modern and responsive web application that is designed to showcase real estate listings. It typically includes features such as OnSale property, a Features section, and a Contact Us section. The website is created using React JS, which
9 min read
Create a Weather app using React and Tailwind
React JS is a very famous library for front-end development. In this article, we will walk through the process of building a weather app using React, a popular JavaScript library for building user interfaces(UI). Here we also use Tailwind CSS, a utility-first CSS framework. Here we also use a weathe
5 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. Weâll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counte
6 min read
Create Feeds UI using React and Tailwind CSS
In the world of social networking, feeds are the primary way users interact with content. Whether it is on LinkedIn, Facebook, or Twitter the feed showcases posts updates, and activities from people or organizations. This article will help you build a LinkedIn-style feed UI using React and Tailwind
4 min read
Create Pagination UI Using React And Tailwind CSS
When working with huge data sets in online applications, pagination is an essential feature. It makes a lengthy list of items easier to browse through by dividing them into digestible parts. This article will tell you how to use Tailwind CSS for styling and React for front-end functionality to creat
3 min read
Build a Contact form Using Django, React and tailwind
This article will guide you in creating a Contact form Using Django, React, and tailwind. Weâll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Contact form. Build a Contact form Using Django, React and TailwindHere, is the step-by-
5 min read
Create Navbars UI using React and Tailwind CSS
A UI plays an important role because a clean, well-designed interface creates a positive first impression and if the UI is good then users can stay on our website some more time and if the UI is bad then they can not stay on our site for more time. we will see how to Create Navbars UI using React an
5 min read
Create Dropdowns UI using React and Tailwind CSS
Dropdown UI components are often used in web applications for forms, navigation, or user preferences, allow users to select from a list of options by clicking a button, which will display a drop-down menu, in this article we will create a dropdown element using React for functionality and Tailwind C
3 min read