We'll create a full-stack web app using: - Django as the backend (using the neat Django Ninja library) - React as the frontend (using TypeScript)
Our aim: create an app that displays a list of trees fetched from a Django API. Very quickly.
Here's a video guide of me building this 🙂:
You can find the finished code for this tutorial on [GitHub](
Part 1: Setting up the Django Backend
Step 1: Create a Django Project
- Open a terminal and create a new directory for your project:
mkdir django-react-app
cd django-react-app
- Create a virtual environment and activate it:
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
- Install Django:
pip install django django-cors-headers django-ninja
- Create a new Django project:
django-admin startproject core .
- Create a new Django app:
python manage.py startapp sim
Step 2: Configure the Django Project
- Open
core/settings.py
and add 'sim' to theINSTALLED_APPS
list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sim', # Add this line
]
- In the same file, add CORS settings to allow requests from your React app:
INSTALLED_APPS = [
# ... other apps ...
'corsheaders', # Add this line
'sim',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Add this line
# ... other middleware ...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:5173", # Add this line (Vite's default port)
]
Step 3: Create the Tree Model
- Open
sim/models.py
and add the following code:
from django.db import models
class Tree(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
- Create and apply migrations:
python manage.py makemigrations
python manage.py migrate
Step 4: Create the API
- Create a new file
sim/api.py
and add the following code:
from ninja import NinjaAPI
from .models import Tree
api = NinjaAPI()
@api.get("/trees")
def list_trees(request):
trees = Tree.objects.all()
return [{"id": tree.id, "name": tree.name} for tree in trees]
- Update
sim/urls.py
to include the API:
from django.urls import path
from .api import api
urlpatterns = [
path('api/', api.urls),
]
- Update
core/urls.py
to include the sim app's URLs:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('sim.urls')),
]
Step 5: Add Some Data
- Open the Django shell to add some trees:
python manage.py shell
Then:
from sim.models import Tree
Tree.objects.create(name="Oak")
Tree.objects.create(name="Pine")
Tree.objects.create(name="Maple")
Tree.objects.create(name="Birch")
Tree.objects.create(name="Willow")
- Run the development server:
python manage.py runserver
- Test the API by visiting
http://localhost:8000/api/trees
. You should see a JSON response with the trees you added.
Part 2: Setting up the React Frontend
Step 1: Create a Vite React Project
- In a new terminal (keep the Django server running), navigate to your project directory and create a new Vite project:
npm create vite@latest vite-project -- --template react-ts
cd vite-project
npm install
Step 2: Update the React App
- Replace the contents of
src/App.tsx
with the following:
import { useEffect, useState } from 'react';
function App() {
interface Tree {
id: number;
name: string;
}
const [trees, setTrees] = useState<Tree[]>([]);
const fetchTrees = async () => {
const response = await fetch('http://localhost:8000/api/trees');
const data = await response.json();
setTrees(data);
};
useEffect(() => {
fetchTrees();
}, []);
return (
<>
<div>List of trees</div>
{trees.map((tree: Tree) => (
<div key={tree.id}>{tree.name}</div>
))}
</>
);
}
export default App;
Step 3: Run the React App
- Start the development server:
npm run dev
- Open
http://localhost:5173
in your browser. You should see the list of trees you added in the Django admin.
Testing and Troubleshooting
- Django API:
- Ensure your Django server is running (
python manage.py runserver
). - Visit
http://localhost:8000/api/trees
to verify the API is working. -
If you don't see any trees, make sure you've added some through the Django shell.
-
React App:
- Check the browser console for any errors.
- If you see a CORS error, make sure you've properly configured CORS in your Django settings.
-
Verify that the fetch URL in
App.tsx
matches your Django server's address and port. -
Data Flow:
- Use browser developer tools to inspect the network requests.
-
Verify that the request to
/api/trees
is being made and returning the expected data. -
Component Rendering:
- Use React Developer Tools to inspect the component state and ensure the
trees
state is being updated correctly.
Remember to test your application thoroughly at each step. If you encounter any issues, double-check your code against the provided examples and ensure all necessary dependencies are installed.
Conclusion
You've now created a basic Django and React application that fetches and displays data from an API!