Serve SPA with Django
#poweredByCaffine
Level: Intermediate
This tutorial will guide you on how to set up for serving SPA (Single Page Application like React, Angular, Vue) through Django.
Django is awesome for startups and for people who want to get work done under tight deadlines as it comes baked in with most of the basics like authentication, as great ORM, sweet sweet admin panel and much more.
Combine it with React.js the frontend framework of my choice I would say its the sweet spot. This tutorial will work just fine with Angular and Vue as well. Just change the react build with respective ones.
Prerequisites:
- python3
- node-js
- create-react-app
Okay, let’s dive into the code:
Let’s prep the directory. I like to keep the backend and frontend into its separate folders. That’s just my preference.
mkdir dogs
# dogs not cats, why? coz even dogs deserve love @catsSuck
create-react-app frontend
mkdir backend
Step 1: Build the SPA
Now its time to build the react app.
cd dogs
npm run build
# patience!!! it will take a minute or 2
This will compile the JSX, optimizes the HTML and CSS resulting in what is known as bundles. You should notice a folder named build has appeared in/frontend/build/
.
Step 2: Prepare the Django
Let’s create a new Django project for the purpose of the demo.
cd ../backend/
python3 -m venv env
source env/bin/activate
pip3 install django
django-admin startproject server .
Now that Django project is set up open /backend/server/settings.py/
and do these edits.
# this is to allow our server to serve on localhostALLOWED_HOSTS = ['*']# let the django django know where to look for templatesTEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['../frontend/build'],
'APP_DIRS': True,
'OPTIONS': {
.......# these help django find the static filesSTATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "../frontend/build/static"),
]
STATIC_ROOT = "static/"
To create a route for SPA chuck these under /backend/server/urls.py
.
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateViewurlpatterns = [
path(‘admin/’, admin.site.urls),
...other routes ...
re_path(‘’, TemplateView.as_view(template_name=”index.html”)),
]
Step 3: Start the server
python manage.py migrate
python manage.py collectstatic
python manage.py runserver
Now if you visit http://127.0.0.1:8000/, you should see the SPA is being served by Django.
brought to you Zenithec Techware [Startup advancingStartups]