How to Serve an Angular Single Page Application using Django – Part 2

Here’s how to serve an Angular frontend and Django REST backend together, optionally in the same Docker container. 

Here’s part 2 of my series of how to serve an Angular 6 SPA web application in Django, without modifying the Angular CLI generated html. 

Running Django and Angular Auto-build Together

I’ve been working on a project that uses Angular on the frontend and Django REST Framework on the backend. Both Django and Angular have their own development servers that feature auto-recompile on change, which is really handy. 

I wanted to have the Angular app served by Django to avoid Cross Origin Request Validation(CORS) and because Django is handling uploaded files. There are other ways to deal with this in development but this is one way to do it.

The development project is structured in such a way that the frontend angular source root is a sub-directory of the Django project root. 

    ... rest of django stuff ...
        ... rest of angular stuff ...

See my article on How to Serve an Angular SPA in Django for the details of how to configure Django to serve the Angular application

I created a shell script to start the two dev servers and called it

#!/usr/bin/env bash

python3 makemigrations
python3 migrate
python3 runserver &

mkdir -p /code/static
cd frontend
npm install
ng build --watch --outputPath=/code/static/

Note: “/code/” may need to be changed to reflect the path to your django project root. In my case I’m serving this is Docker and installing the Django root in /code.

When the script runs it first makes the Django database migrations, loads them into the database server then runs it’s dev server on port 8000. It then makes sure the static files path has been created, installs any angular dependancies and build watches the angular code. 

Note instead of “ng run” I’m using “ng build –watch”. This watches the angular source code path like the ng run command and automatically builds source when it changes. However instead of serving it on port 4200, ng build deploys the compiled SPA to the outputPath, in this case /code/static/.

Put the script in the django root and run it. It’ll first start up Django and then Angular. Angular will take a minute or so to start up before you can access it. 

You’ll only need to stop and restart the script when new files(or dependancies) are added to the Angular app. This is because the ng build option only looks at changes in existing files, it doesn’t detect new files. 

In the next part I’ll show you how to put this all in a Docker container which is useful for keeping a clean development environment.