🚌 In the first part of the series 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.
This application will be the template for our asynchronous AI chat implementation presented in the second and third parts.
✅ If you're just looking for a fast and easy solution to run Django and React together on a single port without proxy configuration, you can use this guide separately from the other parts.
📖 In this series, you can learn about how to build an asynchronous real time AI chat web application using Django Channels and WebSocket. Finally, in the third part of the series we will deploy the web application on Railway.
Python & Node
🔸 The application that is the subject of this tutorial is implemented with Python 3.11.5 and Node 20.10.0.
If you didn't install Python yet, check this website.
Since I use Windows, I also needed nvm-windows for the installation of Node. Follow the instructions and choose installer or manual installation.
After you successfully install nvm-windows, you can add Node. Use a CLI or terminal.
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
Find a place and create a directory for the project with the mkdir
command. I named this my-webapp
, but you can choose another name of course.
mkdir my-webapp
Change directory to this new one.
cd my-webapp
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>
(venv)
means virtual environment is activated. Make sure to always be active during the development process. If you want to exit from venv, just run deactivate
command.
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.
Create Django application
Press Ctrl+C and continue in the command line interface.
I name the Django app backend
.
python manage.py startapp backend
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, you will be asked which language and framework you would like to use. You can choose between JavaScript and TypeScript as the development language and several frontend libraries/frameworks.
As you can see on the image, 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 http://localhost:5173/
, then you should see this:
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')),], # add static directory
'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.
# backend/views.py
from django.views.generic import TemplateView
# React home page
class React(TemplateView):
template_name = 'index.html'
# 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'),
]
Finally, you should set the correct location of static files also in React.
// 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
},
})
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 the app 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;
As you can see, the design is very minimal. Feel free to upgrade it to a cooler one.
/* 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"
3. Hello World
The last step is to change back to the project path, and run the local server.
cd ..
python manage.py runserver
🚀 Open http://localhost:8000/
in your web browser.
🎉 You have now a basic web application, on which you can develop something fascinating. If you stay with me in the next part too, you will see how to add an asynchronous AI-chat with context window to our template. 😊
Top comments (0)