Build a cryptocurrency web app using Django, react, postgresql and tailwind css
- User
Build a cryptocurrency web app using Django, react, postgresql and tailwind css
- Assistant
Build a cryptocurrency web app using Django, react, postgresql and tailwind css
Building a cryptocurrency web application using Django, React, PostgreSQL, and Tailwind CSS involves several steps, from setting up the backend and frontend environments to integrating them seamlessly. Below is a comprehensive guide to help you through the process.
Your cryptocurrency web app will likely include features such as:
We will set up a basic structure covering the essentials, which you can expand upon based on your specific requirements.
Ensure you have the following installed:
First, create a virtual environment to manage your Python dependencies.
# Using virtualenv
python3 -m venv venv
source venv/bin/activate
# Or using pipenv
pip install pipenv
pipenv shell
Install Django and other necessary packages.
pip install django djangorestframework psycopg2-binary django-cors-headers
Ensure PostgreSQL is installed and running. Create a database and a user for your project.
# Access PostgreSQL shell
psql postgres
# Create user
CREATE USER crypto_user WITH PASSWORD 'securepassword';
# Create database
CREATE DATABASE crypto_db;
# Grant privileges
GRANT ALL PRIVILEGES ON DATABASE crypto_db TO crypto_user;
# Exit psql
\q
Initialize your Django project and create an application within it.
django-admin startproject crypto_app
cd crypto_app
python manage.py startapp api
Edit crypto_app/settings.py to configure installed apps, database, REST framework, and CORS.
# crypto_app/settings.py
INSTALLED_APPS = [
# Django default apps...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party apps
'rest_framework',
'corsheaders',
# Your apps
'api',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Add CORS middleware
# Django default middleware...
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# ...
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'crypto_db',
'USER': 'crypto_user',
'PASSWORD': 'securepassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
# CORS settings
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # React dev server
]
# REST Framework settings (optional customization)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
Define your database models. For a basic cryptocurrency app, you might want models like UserProfile, Cryptocurrency, Transaction, etc. Here's a simple example:
# api/models.py
from django.db import models
from django.contrib.auth.models import User
class Cryptocurrency(models.Model):
name = models.CharField(max_length=100)
symbol = models.CharField(max_length=10, unique=True)
current_price = models.DecimalField(max_digits=20, decimal_places=8)
def __str__(self):
return self.name
class Transaction(models.Model):
TRANSACTION_TYPES = (
('BUY', 'Buy'),
('SELL', 'Sell'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='transactions')
cryptocurrency = models.ForeignKey(Cryptocurrency, on_delete=models.CASCADE)
transaction_type = models.CharField(max_length=4, choices=TRANSACTION_TYPES)
amount = models.DecimalField(max_digits=20, decimal_places=8)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.transaction_type} {self.amount} {self.cryptocurrency.symbol} by {self.user.username}"
After defining models, make migrations and migrate:
python manage.py makemigrations
python manage.py migrate
Create serializers to convert models to JSON.
# api/serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Cryptocurrency, Transaction
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email']
class CryptocurrencySerializer(serializers.ModelSerializer):
class Meta:
model = Cryptocurrency
fields = ['id', 'name', 'symbol', 'current_price']
class TransactionSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
cryptocurrency = CryptocurrencySerializer(read_only=True)
cryptocurrency_id = serializers.PrimaryKeyRelatedField(
queryset=Cryptocurrency.objects.all(), source='cryptocurrency', write_only=True
)
class Meta:
model = Transaction
fields = ['id', 'user', 'cryptocurrency', 'cryptocurrency_id',
'transaction_type', 'amount', 'timestamp']
Implement views and URLs for your API.
# api/views.py
from rest_framework import viewsets, permissions
from django.contrib.auth.models import User
from .models import Cryptocurrency, Transaction
from .serializers import UserSerializer, CryptocurrencySerializer, TransactionSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.AllowAny] # Adjust as needed
class CryptocurrencyViewSet(viewsets.ModelViewSet):
queryset = Cryptocurrency.objects.all()
serializer_class = CryptocurrencySerializer
permission_classes = [permissions.AllowAny] # Adjust as needed
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
serializer.save(user=self.request.user)
Set up URL routing using DefaultRouter.
# api/urls.py
from django.urls import path, include
from rest_framework import routers
from .views import UserViewSet, CryptocurrencyViewSet, TransactionViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'cryptocurrencies', CryptocurrencyViewSet)
router.register(r'transactions', TransactionViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Include API URLs in the main project.
# crypto_app/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')), # API routes
]
Run the development server and test your API endpoints.
python manage.py runserver
Visit http://localhost:8000/api/ to see the available endpoints. You can use tools like Postman or curl to test CRUD operations.
Use create-react-app to bootstrap your React frontend.
npx create-react-app frontend
cd frontend
Install Tailwind and its dependencies.
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Set up Tailwind by configuring the tailwind.config.js and including Tailwind in your CSS.
tailwind.config.js:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}", // Adjust paths as needed
],
theme: {
extend: {},
},
plugins: [],
}
src/index.css:
Replace the content with Tailwind directives.
@tailwind base;
@tailwind components;
@tailwind utilities;
Ensure you import index.css in your src/index.js or src/App.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Create components for your application, such as:
Here's an example of a simple cryptocurrency list component fetching data from the backend.
src/components/CryptocurrencyList.js:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const CryptocurrencyList = () => {
const [cryptos, setCryptos] = useState([]);
useEffect(() => {
axios.get('http://localhost:8000/api/cryptocurrencies/')
.then(response => {
setCryptos(response.data);
})
.catch(error => {
console.error('There was an error fetching the cryptocurrencies!', error);
});
}, []);
return (
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">Cryptocurrencies</h1>
<table className="min-w-full bg-white">
<thead>
<tr>
<th className="py-2">Name</th>
<th className="py-2">Symbol</th>
<th className="py-2">Current Price</th>
</tr>
</thead>
<tbody>
{cryptos.map(crypto => (
<tr key={crypto.id} className="text-center">
<td className="py-2">{crypto.name}</td>
<td className="py-2">{crypto.symbol}</td>
<td className="py-2">${crypto.current_price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default CryptocurrencyList;
Set up Axios or Fetch API to communicate with your Django backend. Ensure CORS is properly configured in Django to allow requests from your React frontend.
Install Axios:
npm install axios
You can create a centralized API utility for better management.
src/api.js:
import axios from 'axios';
const API = axios.create({
baseURL: 'http://localhost:8000/api/',
withCredentials: true, // If you need to send cookies
});
// Example: Add authorization header if needed
// API.interceptors.request.use((req) => {
// const token = localStorage.getItem('token');
// if (token) {
// req.headers.Authorization = `Bearer ${token}`;
// }
// return req;
// });
export default API;
Use this API utility in your components to make requests.
Ensure both frontend and backend are running simultaneously during development.
http://localhost:8000/http://localhost:3000/To handle authentication securely, consider implementing token-based authentication (e.g., JWT). Here's a brief outline:
Install djangorestframework-simplejwt for JWT authentication.
pip install djangorestframework-simplejwt
Update crypto_app/settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
# ... other settings
}
Update api/urls.py to include token endpoints:
from django.urls import path
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
# ... existing routes
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
Create login and registration forms in React. Upon successful login, store the JWT tokens (access and refresh) securely, preferably in httpOnly cookies to prevent XSS attacks.
Important: For security, never store JWT tokens in localStorage or sessionStorage if possible. Using httpOnly cookies is more secure.
Example using Axios with JWT:
// Example login function
const login = async (username, password) => {
try {
const response = await axios.post('http://localhost:8000/api/token/', {
username,
password,
});
const { access, refresh } = response.data;
// Store tokens securely
localStorage.setItem('access_token', access);
localStorage.setItem('refresh_token', refresh);
// Set Axios default header
axios.defaults.headers.common['Authorization'] = `Bearer ${access}`;
} catch (error) {
console.error('Login failed:', error);
}
};
Use Axios interceptors to handle token refresh seamlessly.
axios.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = localStorage.getItem('refresh_token');
try {
const response = await axios.post('http://localhost:8000/api/token/refresh/', {
refresh: refreshToken,
});
const { access } = response.data;
localStorage.setItem('access_token', access);
axios.defaults.headers.common['Authorization'] = `Bearer ${access}`;
originalRequest.headers['Authorization'] = `Bearer ${access}`;
return axios(originalRequest);
} catch (refreshError) {
console.error('Refresh token failed:', refreshError);
// Redirect to login
}
}
return Promise.reject(error);
}
);
When moving to production, consider the following:
Backend Deployment:
Frontend Deployment:
npm run build) and serve the static files.Database:
Security:
Environment Configuration:
Scalability:
To make your cryptocurrency app more robust and feature-rich, consider implementing:
Building a cryptocurrency web application with Django, React, PostgreSQL, and Tailwind CSS involves setting up a robust backend API, a responsive and dynamic frontend, and ensuring secure and efficient communication between them. This guide provides a foundational structure to get you started. As you progress, you'll need to delve deeper into each technology to implement advanced features, optimize performance, and ensure security.
Feel free to reach out if you encounter specific issues or need further guidance on particular components of your application!