Blending Django with React Front-end

This is a quick guide on an easy way to work together with Django and ReactJS . The objective is quite simple, but procedure is not so easy.

Anyway, I am trying to apply the shortest solution to integrate these two framework into one hood.

Backend:

Lets create a fresh Django2 project

$ mkvirtualenv mysite -p python3
$ pip install django
$ pip freeze > requirements.txt
$ django-admin startproject mysite
$ cd mysite
$ python manage.py runserver

Now the server should be up and running on http://127.0.0.1:8000/

Project Directory will be as following:

mysite/
mysite/
__init__.py
settings.py
urls.py
wsgi.py
manage.py
requirements.txt

Front-end:

Now we will create a react app using yarn as package manager by the package `create-react-app`

$ yarn add create-react-app
$ yarn create-react-app dashboard
$ cd dashboard
$ yarn start

Now we can now view dashboard in the browser with http://localhost:3000/

Update package.json:

Add following dependencies in package.json file. I am going to use webpack babel-loader for loader engine with preset-env. After that run the command

$ yarn install

Add webpack.config:

Create file webpack.config.js and add these following lines on it for trigger some pre-processing task with webpack and babel-loader to create a bundle folder called assets` inside django project directory. and there will be a config file webpack-stats.json containing the bundle configuration.

After finishing all setup execute -

$ yarn build

This will create assets folder containing all bundles files prepared for django template engine. Every time after new changes in react code need to perform build to update existing bundle pack. The final project structure will be as following -

Make workable 'webpack loader’ in django:

install webpack_loader and update settings.py

$ pip install django-webpack-loader==0.6.0

Add webpack_loader to INSTALLED_APPS in settings.py

INSTALLED_APPS += ['webpack_loader']

Update template variable

Add webpack config variable

Add `STATICFILES_DIRS` to include assets folder to executable

Inject bundle to template:

Create mysite/templates/index.html and add these following lines

Add url for render bundle output:

update mysite/mysite/urls.py by adding these lines

Conclusion:

Hit the url `http://127.0.0.1:8000/` . If everythings are okay then you will see the react output. If not then revise the procedures step-by-step again. thanks, happy coding.