Creating a full-featured web application for your real estate and agricultural enterprise using Django, React, PostgreSQL, and Tailwind CSS is a great choice. This stack allows for a robust backend, a dynamic frontend, a reliable database, and modern styling. Below is a comprehensive guide to help you build your web app step by step.
Table of Contents
- Project Overview
- Prerequisites
- Backend Development with Django
- Setting Up the Django Project
- Configuring PostgreSQL
- Creating Models
- Serializers and Views
- Routing and URLs
- Authentication with JWT
- Frontend Development with React
- Setting Up React App
- Integrating Tailwind CSS
- Creating the UI Components
- State Management (Optional: Redux)
- Connecting to the Backend API
- Connecting Frontend and Backend
- Handling CORS
- API Integration
- Deployment
- Preparing for Production
- Deploying Backend (Heroku, AWS)
- Deploying Frontend (Netlify, Vercel)
- Additional Features
- Search Functionality
- Responsive Design
- Admin Dashboard
- Conclusion
Project Overview
You will build a web application for:
- Selling seedlings and seeds: Users can browse, search, and purchase products.
- Land rental services: Users can view available land for short-term crop farming and initiate rental agreements.
The application will consist of:
- Backend API: Developed with Django and Django REST Framework (DRF).
- Frontend Application: Built with React and styled with Tailwind CSS.
- Database: PostgreSQL to store data related to products, rentals, and users.
Prerequisites
Ensure you have the following installed on your development machine:
- Python 3.8+
- Node.js and npm
- PostgreSQL
- Git
- Virtual Environment Tool (
venv or virtualenv)
Backend Development with Django
Setting Up the Django Project
-
Create a virtual environment and activate it:
python -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
-
Install Django and necessary packages:
pip install django djangorestframework psycopg2-binary
-
Create a new Django project and navigate into it:
django-admin startproject backend
cd backend
Configuring PostgreSQL
-
Set up a PostgreSQL database:
-
Create a new database:
CREATE DATABASE agrienterprise;
-
Create a database user and grant privileges:
CREATE USER agriuser WITH PASSWORD 'yourpassword';
GRANT ALL PRIVILEGES ON DATABASE agrienterprise TO agriuser;
-
Configure the database in backend/settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'agrienterprise',
'USER': 'agriuser',
'PASSWORD': 'yourpassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
Creating Models
We'll create two Django apps: products and rentals.
-
Create the apps:
python manage.py startapp products
python manage.py startapp rentals
-
Add the apps to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
# ... other apps
'rest_framework',
'products',
'rentals',
]
-
Define the models in products/models.py:
from django.db import models
class Product(models.Model):
TYPE_CHOICES = [
('SEED', 'Seed'),
('SEEDLING', 'Seedling'),
]
name = models.CharField(max_length=255)
product_type = models.CharField(max_length=10, choices=TYPE_CHOICES)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
image = models.ImageField(upload_to='product_images/', null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
-
Define the models in rentals/models.py:
from django.db import models
class LandRental(models.Model):
title = models.CharField(max_length=255)
location = models.CharField(max_length=255)
size_in_acres = models.DecimalField(max_digits=5, decimal_places=2)
price_per_month = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
available = models.BooleanField(default=True)
image = models.ImageField(upload_to='rental_images/', null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
-
Run migrations:
python manage.py makemigrations
python manage.py migrate
Serializers and Views
-
Create serializers for the models:
-
In products/serializers.py:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
-
In rentals/serializers.py:
from rest_framework import serializers
from .models import LandRental
class LandRentalSerializer(serializers.ModelSerializer):
class Meta:
model = LandRental
fields = '__all__'
-
Create views using DRF's viewsets:
-
In products/views.py:
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
from rest_framework.permissions import IsAuthenticatedOrReadOnly
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
-
In rentals/views.py:
from rest_framework import viewsets
from .models import LandRental
from .serializers import LandRentalSerializer
from rest_framework.permissions import IsAuthenticatedOrReadOnly
class LandRentalViewSet(viewsets.ModelViewSet):
queryset = LandRental.objects.all()
serializer_class = LandRentalSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
Routing and URLs
-
Set up API routing in backend/urls.py:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from products.views import ProductViewSet
from rentals.views import LandRentalViewSet
router = routers.DefaultRouter()
router.register(r'products', ProductViewSet)
router.register(r'rentals', LandRentalViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
-
Serve media files during development by adding to backend/urls.py:
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
-
Define media settings in backend/settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
Authentication with JWT
-
Install djangorestframework-simplejwt:
pip install djangorestframework-simplejwt
-
Configure authentication classes in settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}
-
Update backend/urls.py to include JWT views:
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns += [
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
-
Create user registration and profile management as needed (optional).
Frontend Development with React
Setting Up React App
-
Navigate to the project root and create a React app:
cd ..
npx create-react-app frontend
cd frontend
-
Install necessary packages:
npm install axios react-router-dom @headlessui/react
Integrating Tailwind CSS
-
Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
-
Configure tailwind.config.js:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
-
Include Tailwind directives in src/index.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
Creating the UI Components
-
Set up routing with react-router-dom:
-
Wrap your app in BrowserRouter in index.js.
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
-
Create pages and components:
- Home Page: Introduction and navigation links.
- Product List and Details: Display products with filtering.
- Rental List and Details: Show available land rentals.
- User Authentication Pages: Login and registration forms.
- Cart and Checkout: For purchasing products.
- Profile Page: User information and order history.
-
Organize components in src/components and pages in src/pages.
-
Example: Fetching products in ProductList.js:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const ProductList = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
axios.get('http://localhost:8000/api/products/')
.then(response => {
setProducts(response.data);
})
.catch(error => {
console.error('Error fetching products:', error);
});
}, []);
return (
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">Products</h1>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
{products.map(product => (
<div key={product.id} className="border p-4 rounded">
<h2 className="text-xl font-semibold">{product.name}</h2>
<p>{product.description}</p>
<p className="font-bold">${product.price}</p>
</div>
))}
</div>
</div>
);
};
export default ProductList;
State Management (Optional: Redux)
If your application grows in complexity, consider using Redux for state management.
-
Install Redux and React-Redux:
npm install redux react-redux
-
Set up the Redux store, actions, reducers, and connect them to your components.
Connecting to the Backend API
-
Set up Axios defaults in src/axiosConfig.js (optional):
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'http://localhost:8000/api/',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
},
});
export default axiosInstance;
-
Use Axios instance in your components to make API calls.
-
Handle authentication by storing JWT tokens and setting them in request headers.
Connecting Frontend and Backend
Handling CORS
-
Install django-cors-headers:
pip install django-cors-headers
-
Add 'corsheaders' to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
# ... other apps
'corsheaders',
]
-
Add CorsMiddleware to MIDDLEWARE:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
# ... other middleware
]
-
Configure allowed origins in settings.py:
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000', # React app URL
]
API Integration
-
Ensure all API endpoints are accessible and test them using tools like Postman.
-
In React, update your API calls to point to the deployed backend when moving to production.
Deployment
Preparing for Production
-
Set DEBUG = False in settings.py.
-
Use environment variables to manage secret keys and sensitive data.
-
Collect static files in Django:
python manage.py collectstatic
-
Configure allowed hosts:
ALLOWED_HOSTS = ['your-domain.com']
Deploying Backend
Option 1: Deploy to Heroku
-
Create a Procfile in the root directory:
web: gunicorn backend.wsgi
-
Install Gunicorn and Whitenoise:
pip install gunicorn whitenoise
-
Update MIDDLEWARE in settings.py before django.middleware.security.SecurityMiddleware:
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
# ... other middleware
]
-
Commit changes and push to Heroku following their deployment guides.
Option 2: Deploy to AWS Elastic Beanstalk
-
Set up an AWS account and Elastic Beanstalk environment.
-
Configure EB CLI and initialize the project.
-
Deploy using EB CLI commands.
Deploying Frontend
Option 1: Deploy to Netlify
-
Build the React app:
npm run build
-
Drag and drop the build folder on Netlify's deployment page or push to a Git repository connected to Netlify.
Option 2: Deploy to Vercel
-
Install Vercel CLI:
npm install -g vercel
-
Deploy the app:
vercel
Configure environment variables for production API endpoints as needed.
Additional Features
Search Functionality
-
Implement search endpoints in your Django views or use filters.
-
Install django-filter and configure DRF to integrate filters.
pip install django-filter
In settings.py:
REST_FRAMEWORK = {
# ... existing configs
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
-
Update viewsets to include filter fields:
class ProductViewSet(viewsets.ModelViewSet):
# ... existing code
filterset_fields = ['name', 'product_type']
-
In React, add search inputs and update API calls with query parameters.
Responsive Design
-
Utilize Tailwind CSS utility classes to make your site responsive.
-
Test the application on different screen sizes and adjust CSS as needed.
Admin Dashboard
-
Customize the Django admin interface or build a custom dashboard.
-
**Use packages like django-admin-interface for enhancements.
pip install django-admin-interface
-
Register models with Django admin in products/admin.py and rentals/admin.py:
from django.contrib import admin
from .models import Product
admin.site.register(Product)
Conclusion
Building this application involves integrating multiple technologies, but by following the steps outlined above, you can create a powerful web app tailored to your enterprise needs. Remember to:
- Plan your project structure and components carefully.
- Test each part individually before integrating.
- Secure your application by handling sensitive data properly.
- Optimize for performance and scalability.
Feel free to expand on this guide by adding features like:
- Email notifications
- Payment processing integration
- Geolocation services
If you need further assistance or clarification on any specific part, don't hesitate to ask!