- Part 1: Configuring Django to Serve an Angular SPA
- Part 2: Running Django and Angular Auto-build Together
- Part 3: Putting it all in a Docker Container
Configuring Django to Serve an Angular SPA
I’ve been working on a blog/gallery web application that has is using Django to provide a RESTful backend API and has an Angular 6 front end client side. In doing this I wanted to have the Angular single page application served by the Django server. Configuring this was a little complicated as there was no clear complete explanation.
Other tutorials do exist, but they require modifying the files generated by the Angular CLI to fit into Django’s templating and static file system. See this for an example: https://medium.com/swlh/django-angular-4-a-powerful-web-application-60b6fb39ef34
Add the dependancies to the requirements.txt:
Add whitenoise to the INSTALLED APPS list in settings.py:
INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ... ]
Configure static files in settings.py:
When deploying your web application, create a “static” directory under the Django project base. Use “ng build” to build your Angular web application, then copy everything from the “dist/<your_angular_app>/” directory to the “static” directory in Angular.
After starting the Django server:
python3 manage.py runserver 0.0.0.0:8000
you should see your Angular SPA start up and run at http://<server>:<port>/. You’ll also be able to access the application via http://<server>:<port>/static/, however all the urls in there will reference /, so it’s best to use the root url.
You can see a full example of this in the pnb gallery project on GitHub.
In the next part I’ll show you how to get the two dev servers running together to autobuild both Django and Angular while having the Angular SPA served by Django.