DEV Community

Gráczol Benedek
Gráczol Benedek

Posted on

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! :)

Top comments (0)