Logo

dev-resources.site

for different kinds of informations.

Using React as Static Files in a Django Application: Step-by-Step Guide

Published at
1/13/2025
Categories
django
react
webdev
tutorial
Author
grbeno
Categories
4 categories in total
django
open
react
open
webdev
open
tutorial
open
Author
6 person written this
grbeno
open
Using React as Static Files in a Django Application: Step-by-Step Guide

🚌 I will guide you through the step-by-step process of creating a basic web application using Django as the back-end and React as the front-end.

💡 Think of it as a foundation for you to build upon later, or as a source of inspiration helping to complete your own project.

👉 If you're looking for a solution to run Django and React under the same URL, serving the React UI as static files for Django, then this post is written for you.

🔧 Prerequisites, tools

I am using the environment below:

If nvm-windows has been installed succesfully on your system, you can add Node.

nvm install <node_version>
Enter fullscreen mode Exit fullscreen mode

Select the latest installed version

nvm use newest
Enter fullscreen mode Exit fullscreen mode

Check Node version

node -v
Enter fullscreen mode Exit fullscreen mode

1. Setting up Django as the back-end

Create a directory for the project. Let's name this my-webapp directory with the command below, or you can choose another name if you prefer.

mkdir my-webapp
Enter fullscreen mode Exit fullscreen mode

Change directory to this new one.

cd my-webapp
Enter fullscreen mode Exit fullscreen mode

1.1 Setup virtual environment

Create virtual environment for the project using venv.

python -m venv venv
Enter fullscreen mode Exit fullscreen mode

Activate the virtual environment.

venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

After the activation command, you should now see something similar:

(venv) PS C:\Apps\my-webapp>
Enter fullscreen mode Exit fullscreen mode

It means virtual environment is activated.

1.2 Install Django and create a project

pip install django
Enter fullscreen mode Exit fullscreen mode
django-admin startproject config .
Enter fullscreen mode Exit fullscreen mode
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000/ in your web browser.

django installation succesful

1.3 Create Django application

Press Ctrl+C and continue in the command line interface.

You can name the Django app whatever you want. My choice now is backend.

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

1.4 Update config/settings.py

Don't forget to add the new app to the list of installed apps in the settings.py.

# config/settings.py

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'backend',  # I've just added
]
Enter fullscreen mode Exit fullscreen mode

2. Setting up React as the frontend

Create React application with Vite. The directory for React files will be frontend but you can choose another name as well.

npm create vite@latest frontend
Enter fullscreen mode Exit fullscreen mode

Create-React

During the process, it will ask you which framework you would like to use, and you can also choose between JavaScript and TypeScript as the development language. As you can see, I have selected here React and JavaScript.

Run the suggested commands to check if the installation was successful.

cd frontend
Enter fullscreen mode Exit fullscreen mode
npm install
Enter fullscreen mode Exit fullscreen mode
npm run dev
Enter fullscreen mode Exit fullscreen mode

Run-Vite

Click on the host's link, then you can see:

Vite

Update files

In order to serve static files from React to Django, you should update settings.py in Django according to this:

# config/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [str(BASE_DIR.joinpath('static')),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
Enter fullscreen mode Exit fullscreen mode
# config/settings.py

STATIC_URL = 'assets/'

STATICFILES_DIRS = [ str(BASE_DIR.joinpath('static', 'assets')) ]
Enter fullscreen mode Exit fullscreen mode

The next step is to create a Django view to render the index.html template, which is an HTML template file and can be developed with React instead of the default Django templating system.

# config/urls.py

from django.contrib import admin
from django.urls import path, re_path
from backend.views import React

urlpatterns = [
    path('admin/', admin.site.urls),

    # React
    re_path(r'^.*', React.as_view(), name='frontend'),
]
Enter fullscreen mode Exit fullscreen mode
# backend/views.py

from django.views.generic import TemplateView

# React home page
class React(TemplateView):
    template_name = 'index.html'
Enter fullscreen mode Exit fullscreen mode

Finally, it is recommended to set the correct location of static files also in React. You can see how to do this below.

// frontend/vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],

  // This ensures that when you run npm run build, Vite places the CSS and JS  files in the correct location that Django expects.

  build: {
    outDir: '../static',  // Output to Django's static folder
    assetsDir: 'assets',  // Put all static assets in an 'assets' directory
  },

})

Enter fullscreen mode Exit fullscreen mode

3. Customizing the welcome page

I delete the files from the src/ directory except for App.jsx App.css main.jsx. After that, you can customize the mentioned files. The welcome page in my case is a simple "Hello World" page, which is enough to start my web application for now.

// frontend/src/main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

Enter fullscreen mode Exit fullscreen mode
// frontend/src/App.jsx

import './App.css';

function App() {
  return (
    <div className="App">
     <h1> Hello World </h1>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
/* src/App.css */

body {
  background: #d7dded;
}

.App {
  text-align: center;
  font-family: 'Courier New', Courier, monospace;
  color: #0c1823;
}

Enter fullscreen mode Exit fullscreen mode

Build the React app after the files are updated.

npm run build
Enter fullscreen mode Exit fullscreen mode

If you encounter the next warning message:

(!) outDir C:\DEV\blog\django-react\static is not inside project root and will not be emptied.
Use --emptyOutDir to override.

Update the src/package.json file with "build": "vite build --emptyOutDir"

The last step is to change back to the project path:

cd ..
Enter fullscreen mode Exit fullscreen mode
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000/ in your web browser.

hello world


Thank you for your attention, I hope this post was useful! :)

django Article's
30 articles in total
Favicon
A Guide to Planning Your API: Code-First VS Design-First Approach
Favicon
Using React as Static Files in a Django Application: Step-by-Step Guide
Favicon
Struggling with Custom Styles in Django_ckeditor_5: My Solution
Favicon
The Core of FastAPI: A Deep Dive into Starlette 🌟🌟🌟
Favicon
Static sites FTW
Favicon
Master Django Admin: A Beginner’s Guide to Managing Your Projects
Favicon
Creating Open Graph Images in Django for Improved Social Media Sharing
Favicon
Not able to connect to PostgreSQL server on Fedora
Favicon
How to upgrade the Python version in a virtual environment
Favicon
Creating a To-do app with HTMX and Django, part 9: active search
Favicon
Learn Django REST Framework Authentication: A Complete Step-by-Step Python Guide
Favicon
Using CSRF Protection with Django and AJAX Requests
Favicon
Introduction to Django Authentication: Understanding the Core Components and Benefits
Favicon
Get Done ✅ : A step-by-step guide in building a Django To Do List
Favicon
Stremlining Development with Daytona
Favicon
npx life@2024 preview: How Missing Flights, Finding Love, and Building Svelte Apps Changed Everything
Favicon
Struggling with Django's HTTPS development server issues? I have written a simple guide to expose your Django project securely using ngrok.
Favicon
Containerizing a Django Web Application: Serving Static Pages with Docker
Favicon
Exposing Your Django Project to the Internet Using Ngrok
Favicon
Django: Find Nearby Users with Coordinates and Radius
Favicon
Integrate Sentry into your Django project
Favicon
Django Authentication Made Easy: A Complete Guide to Registration, Login, and User Management
Favicon
Schedule a call with Twilio and Django
Favicon
What is the Architecture of Django?
Favicon
What is the difference between the extends and include tag in django?
Favicon
Implémentation de vérification de numéro de téléphone dans un projet drf
Favicon
Integrate React into Django Seamlessly with the reactify-django CLI
Favicon
Handling Unmanaged Models in Pytest-Django
Favicon
Mastering Try-Except Blocks in Django: Simplified Python Error Handling
Favicon
Serverless or Server for Django Apps?

Featured ones: