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.
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:
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/
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
webpack.config.js and add these following lines on it for trigger some pre-processing task with
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:
webpack_loader and update
$ pip install django-webpack-loader==0.6.0
webpack_loader to INSTALLED_APPS in
INSTALLED_APPS += ['
Update template variable
Add webpack config variable
Add `STATICFILES_DIRS` to include
assets folder to executable
Inject bundle to template:
mysite/templates/index.html and add these following lines
Add url for render bundle output:
mysite/mysite/urls.py by adding these lines
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.