Angular 6|5 Tutorial: Integrating Angular with Django

In the previous Angular 6 tutorial we've seen how to build a CRUD web application with a Django REST framework API back-end. In this tutorial we'll see how we can integrate the Angular 6 front-end with the Django back-end.

After creating both the back-end and front-end apps we need to integrate them i.e instead of taking the approach where both applications are completely separated, we'll serve the front-end application using a Django view. In development we'll have both Django development server and Angular/Webpack dev server running but for production we'll only need a Django server.

To use this approach you need to tweak the Webpack settings of your front-end project, use the webpack-bundle-tracker (from npm) and use the django-webpack-loader package (from PyPI)

Installing Webpack Bundle Tracker

The webpack-bundle-tracker is a Webpack plugin that generates a stats file containing meta data information about the assets of your front-end application generated by Webpack.

We'll start by installing the webpack-bundle-tracker module then update the Webpack configuration file to make use of this plugin.

npm install webpack-bundle-tracker --save

Ejecting Webpack from Angular 6 CLI

Next you need to eject the Webpack configuration from the Angular 6 CLI using

ng eject

If the ejection is successful you'll find a webpack.config.js in the root of your folder.

Open webpack.config.js and import BundleTracker from webpack-bundle-tracker then locate the plugins entry and add the following code

var BundleTracker = require('webpack-bundle-tracker');

/*...*/
module.exports  = {
    /*...*/
    plugins:[
        /*...*/
        new BundleTracker({filename: '../webpack-stats.json'})
    ]
}

Next add the publicPath setting

"output": {
    "path":  path.join(process.cwd(), "dist"),
    "filename":  "[name].bundle.js",
    "chunkFilename":  "[id].chunk.js",
    "crossOriginLoading":  false,
    "publicPath":"http://127.0.0.1:4200/"//1
},
"devServer": {
    "historyApiFallback":  true,
    "publicPath":  "http://127.0.0.1:4200/",//2
}

If you serve your application you'll have a ../webpack-stats.json in the parent folder i.e the root of the Django project.

After ejecting your Webpack configuration from the Angular 6 CLI you won't be able to use ng serve instead you'll have to use npm run start to serve your application.

This is a screenshot of a project where you can see the webpack.config.js file in the front-end application and a generated webpack-stats.json in the root folder of the project

Angular 6 Django

Next let's install The django-webpack-loader package which will take care of reading the webpack-stats.json and insert the assets in a Django template.

Head back to your terminal the run the following command:

pip install django-webpack-loader

In your settings.py file add webpack_loader to the list of installed apps:

INSTALLED_APPS = [
    #...
    'webpack_loader',
    'core'
]

Then add this configuration object:

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': '',

        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
    }
}

You can find more settings that you can use via this link.

Serving the Angular 6 Application

Now let's create the view to serve the Angular 6 application. Open core/views and add the following view function:

from django.shortcuts import render

def  home(request):
    return render(request, 'core/home.html')

Next you need to create the home.html template so create a templates/core folder inside the core application then add a home.html with the following content:


{% load render_bundle from webpack_loader %}

<html  lang="en">
<head>
<meta  charset="UTF-8">
<base  href="/">
<title>A Simple CRM with Django and Angular 6</title>
</head>
<body>

<app-root></app-root>

{% render_bundle 'inline' %}
{% render_bundle 'polyfills' %}
{% render_bundle 'styles' %}
{% render_bundle 'vendor' %}
{% render_bundle 'main' %}

</body>
</html>

Now you need to add the URL for the home page in urls.py:

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from core import views as coreviews

urlpatterns =[

url(r'^$',coreviews.home),

path('admin/', admin.site.urls)
]

That's it. You should now be able to see your Angular 6 page when visiting the Django web application

Angular 6 Django

Fixing Hot Code Reload

If you change the source code of your front-end application you will not get updates hot code reloaded without manually refreshing the page if you are navigating your application from http://127.0.0.1:8000. That means HCR is not working properly so simply open webpack.config.js and add the following setting:

"devServer": {
    "historyApiFallback":  true,
    "publicPath":  "http://127.0.0.1:4200/",//2,
    "headers": {
        'Access-Control-Allow-Origin':  '\\*'//3
    }
}

That's because http://localhost:8000 sends requests to the Webpack dev server (http://localhost:4200) to get source code changes so we need to update headers to allow request from all origins.

Conclusion

Throughout this tutorial we have integrated both Angular 6 front-end and the Django REST API back-end.

Note: We also publish our tutorials on Medium and DEV.to. If you prefer reading in these platforms, you can follow us there to get our newest articles.

You can reach the author via Twitter:

About the author

Ahmed Bouchefra
is a web developer with 5+ years of experience and technical author with an engineering degree on software development. You can hire him with a click on the link above or contact him via his LinkedIn account. He authored technical content for the industry-leading websites such as SitePoint, Smashing, DigitalOcean, RealPython, freeCodeCamp, JScrambler, Pusher, and Auth0. He also co-authored various books about modern web development that you can find from Amazon or Leanpub


Get our Learn Angular 8 in 15 Easy Steps ebook in pdf, epub and mobi formats, plus a new Angular 8 tutorial every 3 days.


Online Courses (Affiliate)

If you prefer learning with videos. Check out one of the best Angular courses online
Angular 8 - The Complete Guide (2019+ Edition)

Angular Crash Course for Busy Developers

comments powered by Disqus
DMCA.com Protection Status