DEV Community

karthikeyan
karthikeyan

Posted on

Create ReactJS Vite and Django Integration Project

Create ReactJS Vite and Django project

Create ReactJS Vite project

frontend - name of the project

npm create vite@latest 
cd frontend
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Create and Activate Virtual Environment

virtualenv env
cd env
source bin/activate
pip install django djangorestframework django-cors-headers serializer
cd ..
Enter fullscreen mode Exit fullscreen mode

Create Django project

backend - name of the project

django-admin startproject backend
cd backend/
Enter fullscreen mode Exit fullscreen mode

Run the Development Server

python3 manage.py migrate
python3 manage.py runserver
python3 manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Create a App called post

python3 manage.py startapp post
Enter fullscreen mode Exit fullscreen mode

Update Backend Settings

In backend/backend/settings.py:

INSTALLED_APPS = [
    # ...,
    'rest_framework',
    'corsheaders',
    'post',
    # ...,
]

CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',  # Adjust as per your frontend URL
]
MIDDLEWARE = [
    #...
    'corsheaders.middleware.CorsMiddleware',
    #...
]
Enter fullscreen mode Exit fullscreen mode

Create Models

In backend/post/models.py:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()

    def __str__(self):
        return f"Post: {self.title}"
Enter fullscreen mode Exit fullscreen mode

Admin Configuration

In backend/post/admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)
Enter fullscreen mode Exit fullscreen mode

Serializers

Create backend/post/api/serializers.py:

from rest_framework import serializers
from ..models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'title', 'body')
Enter fullscreen mode Exit fullscreen mode

Views and URLs

Create backend/post/api/views.py:

from rest_framework.viewsets import ModelViewSet
from ..models import Post
from .serializers import PostSerializer

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
Enter fullscreen mode Exit fullscreen mode

Create backend/post/api/urls.py:

from django.urls import path
from rest_framework.routers import DefaultRouter
from .views import PostViewSet

router = DefaultRouter()
router.register(r'post', PostViewSet)

urlpatterns = router.urls
Enter fullscreen mode Exit fullscreen mode

Root URLs

In backend/backend/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('post.api.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Run the Application

python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py runserver
Enter fullscreen mode Exit fullscreen mode

create .env file in /frontend/.env

VITE_API_URL=http://127.0.0.1:8000/api/
Enter fullscreen mode Exit fullscreen mode

write the bellow code

import { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}post/`);
        if (!response.ok) {
          throw new Error('Network response was not ok...');
        }
        const result = await response.json();
        console.log(result)
        setData(result);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    fetchData(); 
  }, []); 
  return (
    <>
      <h1>Hello World!..</h1>
      {data.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </div>
      ))}
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Run the Application

python3 manage.py makemigrations
python3 manage.py migrate
npm run dev
python3 manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Open your Browser

Access the application using http://localhost:5173/

Access the application django page using http://127.0.0.1:8000/api/

Access the application django Admin page using http://127.0.0.1:8000/admin/login/?next=/admin/



Top comments (0)