Django with DRF and ReactJS Connections
1.
Prerequisites
Before
we begin, ensure you have:
- Python
installed (3.x)
- Node.js
and npm installed
- Basic
knowledge of Python, JavaScript, and command line usage
2.
Setting Up Django with Django Rest Framework
Step 1: Install
Django and DRF
Open
your terminal and create a new directory for your project:
Bash
mkdir
django-react-example
cd
django-react-example
Set
up a virtual environment (optional but recommended):
Bash
python
-m venv venv
source
venv/bin/activate # On Windows use
`venv\Scripts\activate`
Install
Django and Django Rest Framework:
Bash
pip
install django djangorestframework
Step 2: Create a
Django Project
Create
a new Django project:
Bash
django-admin
startproject myproject
cd myproject
Create
a new Django app:
Bash
python
manage.py startapp myapp
Step 3: Configure
Django
Edit
myproject/settings.py
to include the new app and DRF:
Python
INSTALLED_APPS
= [
...
'rest_framework',
'myapp',
]
Step 4: Create a
Simple API
In
myapp/models.py,
create a simple model:
Python
from
django.db import models
class
Item(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
Run
migrations:
Bash
python
manage.py makemigrations
python
manage.py migrate
Create
a serializer in myapp/serializers.py:
Python
from
rest_framework import serializers
from
.models import Item
class
ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
Create
a view in myapp/views.py:
Python
from
rest_framework import viewsets
from
.models import Item
from
.serializers import ItemSerializer
class
ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
Add
routes in myproject/urls.py:
Python
from
django.urls import path, include
from
rest_framework.routers import DefaultRouter
from
myapp.views import ItemViewSet
router
= DefaultRouter()
router.register(r'items',
ItemViewSet)
urlpatterns
= [
path('api/', include(router.urls)),
]
Step 5: Run the
Django Server
Run
the server:
Bash
python
manage.py runserver
Visit
http://127.0.0.1:8000/api/items/
to see the API in action.
3.
Setting Up React.js
Step 1: Install
Node.js and Create React App
If
you haven’t already, install Create React App:
Bash
npx
create-react-app frontend
cd
frontend
Step 2: Create a
Simple React App
In
your React app directory, open src/App.js
and modify it:
Javascript
import
React, { useEffect, useState } from 'react';
function
App() {
const [items, setItems] = useState([]);
useEffect(() => {
fetch('http://127.0.0.1:8000/api/items/')
.then(response => response.json())
.then(data => setItems(data));
}, []);
return (
<div>
<h1>Items</h1>
<ul>
{items.map(item => (
<li
key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export
default App;
Step 3: Start the
React App
Run
the React app:
Bash
npm
start
Visit
http://localhost:3000
to see your React app displaying data from your Django API.
4.
Connecting React with Django
Make
sure your Django server is running. If you encounter CORS issues, install django-cors-headers:
Bash
pip
install django-cors-headers
Add
it to INSTALLED_APPS
in settings.py and configure it:
Python
MIDDLEWARE
= [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ALLOWED_ORIGINS
= [
"http://localhost:3000",
]
5.
Summary
You’ve
set up a simple application using Django, Django Rest Framework, and React.js.
- Backend
(Django + DRF): You created a
simple API that allows you to manage a list of items.
- Frontend
(React.js): You created a simple React
application that fetches and displays data from your Django API.
Step-by-Step Guide
1. Set Up the Backend (Django + DRF)
A.
Install Required Tools
- Install
Python:
Make sure Python (3.x) is installed on your machine.
- Install
Node.js:
Ensure you have Node.js and npm installed.
B.
Create a New Django Project
- Open
your terminal (Command Prompt, PowerShell, or Terminal).
- Create
a new directory for your project:
Bash
mkdir
django-react-example
cd
django-react-example
- Set
up a virtual environment:
Bash
python
-m venv venv
source
venv/bin/activate # On Windows use
`venv\Scripts\activate`
- Install
Django and Django Rest Framework:
Bash
pip
install django djangorestframework
C.
Create Django Project and App
- Create
a new Django project:
Bash
django-admin
startproject myproject
cd
myproject
- Create
a new app:
Bash
python
manage.py startapp myapp
D. Configure Django Settings
- Open
myproject/settings.py
and add 'rest_framework'
and 'myapp'
to INSTALLED_APPS:
Python
INSTALLED_APPS
= [
...
'rest_framework',
'myapp',
]
E.
Create a Simple API
- Define
a Model:
In myapp/models.py,
add:
Python
from
django.db import models
class
Item(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
- Run
migrations:
Bash
python
manage.py makemigrations
python
manage.py migrate
- Create
a Serializer: In myapp/serializers.py,
add:
Python
from
rest_framework import serializers
from
.models import Item
class
ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
- Create
a View:
In myapp/views.py,
add:
Python
from
rest_framework import viewsets
from
.models import Item
from
.serializers import ItemSerializer
class
ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
- Add
Routes:
In myproject/urls.py,
add:
Python
from
django.urls import path, include
from
rest_framework.routers import DefaultRouter
from
myapp.views import ItemViewSet
router
= DefaultRouter()
router.register(r'items',
ItemViewSet)
urlpatterns
= [
path('api/', include(router.urls)),
]
F.
Run the Django Server Run the server:
Bash
python
manage.py runserver
Check
if your API works by visiting http://127.0.0.1:8000/api/items/.
2. Set Up the
Frontend (React)
A.
Create a React App
- In
your terminal (outside the Django project directory), create a React app:
Bash
npx
create-react-app frontend
cd
frontend
B.
Modify the React App
- Open
src/App.js
and replace its content with:
Javascript
import
React, { useEffect, useState } from 'react';
function
App() {
const [items, setItems] = useState([]);
useEffect(() => {
fetch('http://127.0.0.1:8000/api/items/')
.then(response => response.json())
.then(data => setItems(data));
}, []);
return (
<div>
<h1>Items</h1>
<ul>
{items.map(item => (
<li
key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export
default App;
C.
Start the React App Run the React app:
Bash
npm
start
Visit
http://localhost:3000
to see the data fetched from your Django API.
3. Handle CORS Issues
(if needed)
- Install
django-cors-headers:
Bash
pip
install django-cors-headers
- Add
it to INSTALLED_APPS
in settings.py
and configure it:
Python
INSTALLED_APPS
= [
...
'corsheaders',
]
MIDDLEWARE
= [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ALLOWED_ORIGINS
= [
"http://localhost:3000",
]
No comments:
Post a Comment