Wednesday, October 9, 2024

Django with DRF and ReactJS Connections

 Follow me


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

  1. Install Python: Make sure Python (3.x) is installed on your machine.
  2. Install Node.js: Ensure you have Node.js and npm installed.

B. Create a New Django Project

  1. Open your terminal (Command Prompt, PowerShell, or Terminal).
  2. Create a new directory for your project:

Bash

 

mkdir django-react-example

cd django-react-example

  1. Set up a virtual environment:

Bash

 

python -m venv venv

source venv/bin/activate  # On Windows use `venv\Scripts\activate`

  1. Install Django and Django Rest Framework:

Bash

 

pip install django djangorestframework

C. Create Django Project and App

  1. Create a new Django project:

Bash

 

django-admin startproject myproject

cd myproject

  1. Create a new app:

Bash

 

python manage.py startapp myapp

D. Configure Django Settings

  1. Open myproject/settings.py and add 'rest_framework' and 'myapp' to INSTALLED_APPS:

Python

 

INSTALLED_APPS = [

    ...

    'rest_framework',

    'myapp',

]

E. Create a Simple API

  1. 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

  1. Run migrations:

Bash

 

python manage.py makemigrations

python manage.py migrate

  1. 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__'

  1. 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

  1. 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

  1. 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

  1. 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)

  1. Install django-cors-headers:

Bash

 

pip install django-cors-headers

  1. 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

Online Calculator

Follow Me 0 C % / * 7 8 9 - 4 5 6 +...