DEV Community

grbeno
grbeno

Posted on • Edited on

Real-Time AI Chat with Django and React: Template

🚌 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>
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

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
Enter fullscreen mode Exit fullscreen mode

Change directory to this new one.

cd my-webapp
Enter fullscreen mode Exit fullscreen mode

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

(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
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

Create Django application

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

I name the Django app backend.

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

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, 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
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 http://localhost:5173/, then you should see this:

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')),],  # 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',
            ],
        },
    },
]
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.

# 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
# 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

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
  },

})

Enter fullscreen mode Exit fullscreen mode

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>,
)

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

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;
}

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"


3. Hello World

The last step is to change back to the project path, and run the local server.

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


🎉 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)