🚌 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:
- Windows 11 Pro
- PowerShell/CLI
- Python 3.11.5
- nvm-windows for installing Node
If nvm-windows has been installed succesfully on your system, you can add Node.
nvm install <node_version>
Select the latest installed version
nvm use newest
Check Node version
node -v
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
Change directory to this new one.
cd my-webapp
1.1 Setup virtual environment
Create virtual environment for the project using venv.
python -m venv venv
Activate the virtual environment.
venv\Scripts\activate
After the activation command, you should now see something similar:
(venv) PS C:\Apps\my-webapp>
It means virtual environment is activated.
1.2 Install Django and create a project
pip install django
django-admin startproject config .
python manage.py runserver
Open http://localhost:8000/
in your web browser.
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
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
]
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
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
npm install
npm run dev
Click on the host's link, then you can see:
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',
],
},
},
]
# config/settings.py
STATIC_URL = 'assets/'
STATICFILES_DIRS = [ str(BASE_DIR.joinpath('static', 'assets')) ]
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'),
]
# backend/views.py
from django.views.generic import TemplateView
# React home page
class React(TemplateView):
template_name = 'index.html'
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
},
})
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>,
)
// frontend/src/App.jsx
import './App.css';
function App() {
return (
<div className="App">
<h1> Hello World </h1>
</div>
);
}
export default App;
/* src/App.css */
body {
background: #d7dded;
}
.App {
text-align: center;
font-family: 'Courier New', Courier, monospace;
color: #0c1823;
}
Build the React app after the files are updated.
npm run build
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 ..
python manage.py runserver
Open http://localhost:8000/
in your web browser.
Thank you for your attention, I hope this post was useful! :)
Top comments (0)