3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger

3 horizontal lines, burger
Remove all
LOADING ...

Content



    Integrating a React app into a Django project p. 1

    Clock
    03.08.2024
    /
    Clock
    02.10.2025
    /
    Clock
    7 minutes
    An eye
    510
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0

    Intoduction

    In this article, I will show you how to integrate a React application into a Django project. The idea is that Django renders its templates, and React modifies them as needed.
    If you want to skip the basic setup and move on to the React integration part. Also you can download a ready-made project for it.

    Create a Django project

    We will start by creating a root directory for our project.
    mkdir SearchResultParser cd SearchResultParser
    Now, create and activate a virtual environment, for windows.
    python -m venv .venv .venv\Scripts\Activate.ps1
    Commands for linux:
    python -m venv .venv source ./.venv/Scripts/activate
    After activating a virtual environment, we have to install django package and start a new project. Let’s call it a Website.
    pip install django django-admin startproject Website cd Website
    If everything is done right, we will successfully launch a project. Just like that:
    python ./manage.py runserver

    Create a Backend app

    Now, we need to install a couple of new Python packages to configure our Backend app. These packages:
    1. django-cors-headers: for enabling so-called Cross-Origin Resource Sharing (CORS) for communication between React app and Django API.
    2. djangorestframework: a Django app that allows us to build an API for further use.
    Install and configure our first Django app:
    pip install djangorestframework django-cors-headers python ./manage.py startapp Backend
    Edit the settings.py file using your favorite text editor. In my case, it is NeoVim. We will link the newly created app and those that we installed earlier.
    INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Backend.apps.BackendConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ]
    Create an urls.py file for linux:
    touch Backend/urls.py
    For windows machines:
    Get-Item Backend/urls.py
    Paste the next content in the urls.py file in the Website folder:
    from django.contrib import admin from django.urls import path, include from rest_framework import routers from Backend import views router = routers.DefaultRouter() router.register(r'results', views.BackendModelView, 'result') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ]
    Here we imported routers for rest_framework and views from our Backend app and then included them into urlpatterns. The next thing we will do is to create a placeholder model for now. In the Backend/models.py file paste:
    from django.db import models class BackendModel(models.Model): title = models.CharField(max_length=120) description = models.TextField() def _str_(self): return self.title
    And link our model with the default Django admin app, in the Backend/admin.py file paste:
    from django.contrib import admin from .models import BackendModel class BackendModelAdmin(admin.ModelAdmin): list_display = ('title', 'description') admin.site.register(BackendModel, BackendModelAdmin)
    To work, the rest framework needs to have a serializer class. What he does is convert Django models into JSON files for us. Open(Create) a Backend/serializers.py file and paste next content:
    from rest_framework import serializers from .models import BackendModel class BackendModelSerializer(serializers.ModelSerializer): class Meta: model = BackendModel fields = ('id', 'title', 'description')
    The last thing we need to do is create a specific view class for BackendModel. Open the Backend/views.py file and add the next lines:
    from django.shortcuts import render from rest_framework import viewsets from .serializers import BackendModelSerializer from .models import BackendModel class BackendModelView(viewsets.ModelViewSet): serializer_class = BackendModelSerializer queryset = BackendModel.objects.all()
    At the end, create all migrations and apply them, also create a super user to gain access to the database:
    python ./manage.py makemigrations python ./manage.py migrate python ./manage.py createsuperuser

    Create a Frontend app

    It is time for the Frontend app. This app is going to contain our React app. But first, we need to create, link, and prepare this app. As always, nothing changed:
    python ./manage.py startapp Frontend
    In the settings.py file, link it:
    INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Backend.apps.BackendConfig', 'Frontend.apps.FrontendConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ]
    And in the Frontend/urls.py file, add the view:
    from django.urls import path from .views import main urlpatterns = [ path('', main, name='main') ]
    And create a new view function in Frontend/views.py file:
    from django.shortcuts import render def main(request): return render(request, 'Frontend/app.html')
    To render something, we need to create an HTML file, and folder along the way too:
    mkdir Frontend/templates mkdir Frontend/templates/Frontend Get-Item Frontend/templates/Frontend/app.html
    And include the created earlier Frontend/urls.py file in the Website/urls.py.
    from django.contrib import admin from django.urls import path, include from rest_framework import routers from Backend import views router = routers.DefaultRouter() router.register(r'results', views.BackendModelView, 'result') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('', include('Frontend.urls')), ]

    React installation

    Now it is time for React installation. It is relatively easy if you know what to install ;). Go to the Frontend directory and create some directories:
    cd Frontend mkdir static mkdir static/js #For scripts mkdir static/img #For images mkdir static/css #For styles mkdir src mkdir src/components # For ReactJS components
    Why don't we add a Frontend folder to the static folder like usual? We might have to create another Django app, and since we want to use React throughout the site, we haven't created a Frontend folder.
    At this step, the Frontend app is ready, and the last thing to do is to create and configure the React app. I hope you already have a npm.
    npm init -y
    Install initial packages, one by one:
    1. webpack to bundle all of our JS code
    2. babel for translating all of our JS and CSS code into friendly types for each browser.
    3. react for developing all of our frontend parts of the website
    npm i webpack webpack-cli --save-dev ; npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-dev ; npm i react react-dom --save-dev ; npm install @babel/plugin-proposal-class-properties ; npm install react-router-dom;
    Do not try to combine all of the above shell’s commands into a single one. Node.js could not handle all of it at once. After installing the required packages, we need to configure Babel.
    After installing the necessary packages, you need to configure Babel. Create a configuration file; name it babel.config.json. And paste the following configuration code:
    { "presets": [ [ "@babel/preset-env", { "targets": { "node": "10" } } ], "@babel/preset-react" ], "plugins": ["@babel/plugin-proposal-class-properties"] }
    Now let's set up the webpack package, but first let's create a configuration file. Name this file webpack.config.js. And insert the following configuration code:
    const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/js"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], };
    Now, let's do a little magic in the package.json file. To be more specific, we'll add two scripts to manage npm:
    { "name": "frontend", "version": "1.0.0", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "prod": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/preset-react": "^7.24.7", "babel-loader": "^9.1.3", "react": "^18.3.1", "react-dom": "^18.3.1", "webpack": "^5.93.0", "webpack-cli": "^5.1.4" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.18.6", "react-router-dom": "^6.25.1" } }

    Creating first react component

    После того как мы всё настроили давай напишем немного react кода. В папке Frontend/src, создай файл index.js, а в папке Frontend/src/components, создай файл App.js. Теперь вставим временный код в созданный файл src/components/App.js:
    After we have everything set up, let's write some react code. In the Frontend/src folder, create a file called index.js, and in the Frontend/src/components folder, create a file called App.js. Now paste the temporary code into the created file src/components/App.js:
    import React from 'react'; import { createRoot } from 'react-dom/client'; const App = () => { return <h1>Rendered by Django, cooked by React</h1>; }; export default App; const container = document.getElementById('app'); const root = createRoot(container); root.render(<App />);
    We need to include the App component in src/index.js file. Paste this:
    import App from './components/App';
    At the end, we need to paste this example code into the app.html file. His location is Frontend/templates/Frontend/app.html.
    {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>React with Django</title> </head> <body> <div id="app"></div> <script src="{% static 'js/main.js' %}"></script> </body> </html>
    Everything is set up. Now let's test it. First, start the Django server, then the webpack server using the script you created earlier:
    python ./manage.py runserver npm run dev
    If you did all right, you will see something like this.

    Conclusion

    All begins with Django’s rendered template. After this, React is going to find a div by id “app” and render our h1 tag. Now we have a full-stack app that is ready to be developed. (❁´◡`❁)
    If you skipped all of the above and just want a ready-to-use solution, here it is. An archive with preconfigured folder structure and precalculated dependencies. All you need to do is set up a virtual environment (install all required Python packages) for the downloaded folder and install the required NPM packages in the Frontend app.
    In the next article, I will show you the basic layout for a website and what it is going to look like.

    Common errors, bugs and mistakes

    Incorrect Project Structure

    Mistake: Not organizing the project directory properly, leading to confusion and difficulties in managing both React and Django codebases.
    Solution: Maintain a clear and logical directory structure. Keep frontend and backend code in separate directories.

    Ignoring CORS Issues

    Mistake: Overlooking Cross-Origin Resource Sharing (CORS) settings, which can lead to blocked requests.
    Solution: Configure your Django backend to handle CORS. Use django-cors-headers to allow specific origins.

    Inconsistent Environment Configuration

    Mistake: Having conflicting or inconsistent environment configurations, leading to issues in development and production builds.
    Solution: Ensure that environment variables are consistently defined. Use tools like dotenv for managing environment variables in both React and Django.

    Incorrectly Handling Static Files

    Mistake: Misconfiguring static file handling, which can lead to issues in serving React assets in Django.
    Solution: Properly configure Django to serve static files and ensure React assets are placed in a directory Django can serve.

    Ignoring Client-Side Routing Conflicts

    Mistake: Ignoring potential conflicts between Django's and React Router's routing mechanisms, leading to broken links or incorrect routing.
    Solution: Delegate client-side routing to React Router and ensure Django serves the React app for all relevant routes.

    Do not forget to share, like and leave a comment :)

    Comments

    (0)

    captcha
    Send
    LOADING ...
    It's empty now. Be the first (o゚v゚)ノ

    Other

    Similar articles


    React and Django REST API. How to integrate one into another and how to use

    Clock
    24.07.2024
    /
    Clock
    02.10.2025
    An eye
    436
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article, I will describe a process of integrating the React framework with the Django website. We will configure a communication API between both of them. Also, a TailwindCSS …

    Developing frontend part of a website with React on Django | SearchResultParser p. 2

    Clock
    16.08.2024
    /
    Clock
    02.10.2025
    An eye
    667
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    I show and tell how to develop a frontend for a site on React with a backend on django. I use MaterialUI and TailwindCSS, with source code and comments.

    A new project, codename: SearchResultParser | Tim the Webmaster

    Clock
    16.07.2024
    /
    Clock
    05.10.2025
    An eye
    192
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    I will be busy developing a new project. His name is SearchResultParser. Its essence is to parse data from the search results of various search engines, such as google, youtube, …

    An example of the integration of Django with allauth. Frontend on ReactJS

    Clock
    31.01.2025
    /
    Clock
    02.10.2025
    An eye
    1391
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    1
    In this article I will describe the process of integrating allauth into a Django project. Frontend is handled by React. I will configure a registration and an authorization process by …

    How to implement yourown API using Django rest framework

    Clock
    24.02.2025
    /
    Clock
    02.10.2025
    An eye
    673
    Hearts
    1
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    This article describes the process of setting up and adding a REST framework to a site written in Django. It is added in order to build an API for access …

    Used termins


    Related questions