Basic Django and React Setup: A Step-by-Step Guide

shaniya_khan_8d7f203b1ad2

Shaniya Khan

Posted on September 11, 2024

Basic Django and React Setup: A Step-by-Step Guide

Using React with Django offers the flexibility of a modern frontend paired with Django's robust backend and admin interface.

Even though react is used with NodeJS usually which seems to be a good option, what if we use it with Django, which comes with a pre-created admin panel? Wouldn't that be great? There is no hassle of creating the whole interface and frontend for it, we can just use Django's admin panel.

Sooooo... Let's get Started with it....

Step 1: Set Up Your Development Environment

Ensure the following tools are installed:

  • Python (for Django)
  • Node.js (for React/Next.js)
  • SQLite (for your database, SQLite is fine for development)
  • Git (for version control)
  • Virtualenv (for Python virtual environments)

Step 2: Create the Django Backend

1. Create a virtual environment for your Django project:

  • Create a Director for your project where we will have both frontend and backend folders. I have created mine as 'shaniya' and use the cd command to go inside the directory through the terminal.

Terminal ScreenShot

  • Create a virtual environment

Terminal ScreenShot

Command for you to copy

python -m venv env
Enter fullscreen mode Exit fullscreen mode
  • Activate virtual environment

Terminal ScreenShot

the '(env)' beside the path indicates that the Virtual environment is activated

2. Install Django using your terminal

Terminal ScreenShot

Command for you to copy

pip install django
Enter fullscreen mode Exit fullscreen mode

3. Follow the following command to create a Django project inside your project directory:

Terminal ScreenShot

Command for you to copy

django-admin startproject portfolio_backend
Enter fullscreen mode Exit fullscreen mode

4. Create a Django App

Terminal Screenshot

Command for you to copy

python manage.py startapp portfolio
Enter fullscreen mode Exit fullscreen mode

5. Install Django Rest Framework

pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode

6. Set Up Models for Projects
We are creating a simple model named 'Project' having 4 fields.
Edit portfolio/models.py to define your project data structure:

from django.db import models

class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    link = models.URLField()
    image = models.ImageField(upload_to='projects/', blank=True, null=True)

    def __str__(self):
        return self.title
Enter fullscreen mode Exit fullscreen mode

7. Set Up Serializers and Views for API

Install Django REST Framework and configure it in settings.py:

INSTALLED_APPS = [
    'rest_framework',
    'portfolio',
    ...
]
Enter fullscreen mode Exit fullscreen mode

Create portfolio/serializers.py and add the following code to it:

from rest_framework import serializers
from .models import Project

class ProjectSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()

    class Meta:
        model = Project
        fields = ['id', 'title', 'description', 'link', 'image']

    def get_image(self, obj):
        request = self.context.get('request')
        if obj.image:
            return request.build_absolute_uri(obj.image.url)
        return None
Enter fullscreen mode Exit fullscreen mode

In portfolio/views.py, create an API view:

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Project
from .serializers import ProjectSerializer

class ProjectListView(APIView):
    def get(self, request):
        projects = Project.objects.all()
        serializer = ProjectSerializer(projects, many=True, context={'request': request})
        return Response(serializer.data)
Enter fullscreen mode Exit fullscreen mode

8. Set Up URLs

Edit portfolio_backend/urls.py to add an API route:

from django.contrib import admin
from django.urls import path, include
from portfolio.views import ProjectListView
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('projects/', ProjectListView.as_view(), name='project-list'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Enter fullscreen mode Exit fullscreen mode

9. Add Media Settings to settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Enter fullscreen mode Exit fullscreen mode

10. Ensure you have CORS set up correctly in Django.

pip install django-cors-headers
Enter fullscreen mode Exit fullscreen mode

Add it to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    # other apps
    'corsheaders',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    # other middleware
]

# Allow CORS for localhost (or adjust for your needs)
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # React frontend
]
Enter fullscreen mode Exit fullscreen mode

11. Register the Model in admin.py

from django.contrib import admin
from .models import Project

# Register your models here.
admin.site.register(Project)
Enter fullscreen mode Exit fullscreen mode

12. Run Migrations

  • Create migration files:
python manage.py makemigrations
Enter fullscreen mode Exit fullscreen mode
  • Apply migrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

13. Access the Django Admin

Create a superuser to access the Django admin panel, run the following command and follow the instructions on terminal to setup user and password.

python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

14. Run Backend Server

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Once the Server is running and the superuser is created, navigate to the admin page at http://localhost:8000/admin, and you should see the Project model listed there.

Django Admin panel

Step 3: Create the Next.js Frontend

1. Set Up a New Next.js Project

Inside 'shaniya/' run the following commands in the terminal

npx create-next-app@latest frontend
cd frontend
npm install
Enter fullscreen mode Exit fullscreen mode

2. Fetch Data from Django Backend

In frontend/src/page.tsx, set up an API call to fetch data from the Django backend:

"use client"; // Add this line to treat this component as a client component

import { useEffect, useState } from 'react';
import axios from 'axios';

// Define interface for the API response
interface Project {
  id: number;
  title: string;
  description: string;
  link: string;
  image?: string;
}

export default function Home() {
  const [projects, setProjects] = useState<Project[]>([]);

  useEffect(() => {
    axios.get<Project[]>('http://localhost:8000/projects/')
      .then((response) => {
        setProjects(response.data);
      })
      .catch((error) => console.error(error));
  }, []);

  return (
    <div>
      <h1>My Portfolio</h1>
      <div>
        {projects.map((project) => (
          <div key={project.id}>
            <h2>{project.title}</h2>
            <p>{project.description}</p>
            <a href={project.link}>View Project</a>
            {project.image && <img src={project.image} alt={project.title} />}
          </div>
        ))}
      </div>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

15. Run the Frontend

npm run dev
Enter fullscreen mode Exit fullscreen mode

The frontend will be available at http://localhost:3000.

Add some data to the project through the admin panel in django and it should be visible on the react frontend.

Final Output

Congratulations, you just learned how to connect django backend to react frontend.

What Next?

Now that you've connected Django with Next.js, here are a few ways to expand your project:

  • Add Authentication: Implement user sign-up and login using Django’s built-in authentication or JWT, and handle sessions on the front end with libraries like next-auth.
  • Deploy Your App: Host your Django backend on platforms like Heroku or AWS, and deploy your Next.js frontend on Vercel for a live production environment.
  • Enhance Models & APIs: Add more complex models (e.g., blog or e-commerce) and build out full CRUD APIs in Django.
  • Improve Frontend: Use state management tools like Redux or Context API for a scalable frontend architecture, or integrate React Query for API handling.
  • Add File Uploads: Allow users to upload images or files via the frontend, handled by Django's file fields.

Feel Free to connect if you encounter any issues or need any help.

Happy Learning :)

💖 💪 🙅 🚩
shaniya_khan_8d7f203b1ad2
Shaniya Khan

Posted on September 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related