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

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

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

I didn’t want to have to do this. Using Whitenoise and Django SPA, you can serve the Angular application without modification. 

Add the dependancies to the requirements.txt:

whitenoise
django-spa

Add whitenoise to the INSTALLED APPS list in settings.py:

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    ...
]

Configure static files in settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_STORAGE = 'spa.storage.SPAStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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.