Integrating Django web framework with ReactJS
- In your System, You should have installed Django, if not then go here, and install it and if you are using virtualenv to install, then its a better way.
- After this, you need to install npm and reactjs in your System. To install react execute
npm install --save-dev react react-dom
- For reactJS, you need to install webpack-loader to keep a bridge between django and reactJS. To install webpack, execute
pip3 install django-webpack-loader
- Create Django project. If you don’t know the steps then please follow this. I have created one django project named as ‘django_react’.
- Then create one application in that project. I have created app named as ‘my_app’.
- Create one folder name as ‘templates’ in my_app folder. e.g. my_app/templates and ‘asset’ inside django_react folder which is our project folder.
Now Django configurations are done, let’s configure npm:
- Generate a package.json inside your project’s root folder using command
npm initNow npm will ask you for some information, provide it and hit Enter.
- Now setting up all the modules of webpack using command
npm install webpack webpack-bundle-tracker babel babel-loader babel-core babel-preset-es2015 babel-preset-react --save-dev
- After installing the required dependencies we need a config file for Webpack to tell it what to do . Let’s navigate to your project root folder then execute touch webpack.config.js Then add this :
Make sure you create the folders assets and js for our assets:
mkdir -p assets/js
Loaders are plugins used by Webpack to add functionality.
npm install babel-loader babel-core babel-preset-es2015 babel-preset-react --save-dev
Now lets create a babel configuration file :
Navigate to your project’s root folder then execute touch .babelrc Then open it and add :
Now let’s create bundles folder in assets. Navigate to your project root folder then execute ./node_modules/.bin/webpack -d
Here is our project folder structure:
│ └── js/
│ └── bundles/
Now let’s add this bit of code in our template which is inside the templates folder e.g. templates/my_app/index.html
Now add this in views.py:
Now let’s update settings.py :
Add this in index.js :
And Finally, for automatically create a bundle in bundles folder execute this ./node_modules/.bin/webpack–config webpack.config.js–watch
At BoTree Technologies, we build enterprise applications with our Django team of 20+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management