Django-React Hello World

Django-React Hello World

·

3 min read

Hello, In this article today we are going to integrate react and django and then write a hello world program, Django will be used for backend configurations while react will be used for the front end configurations, Lets get started

requirements 1 Node 2 npm 3 Django 4 Python

Make sure you download the following from their official sites and have the latest versions installed in your PC

Now Create a folder

Then in the same folder create a django project

C:\Users\LENOVO\Desktop\django-react>django-admin startproject backend_django

The structure looks like this

Screenshot (135).png

Now create a react app

C:\Users\LENOVO\Desktop\django-react>npx create-react-app frontend_react

Creating a new React app in C:\Users\LENOVO\Desktop\django-react\frontend_react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template... 
// wait untill compeletion

The structure looks like this

Screenshot (136).png

Now drag the frontend_react project and drop it in your django project

open the setings.py file in the django project add this in the TEMPLATE --> DIRS

'DIRS': [os.path.join(BASE_DIR,'frontend_react/build')],

should look like this after change


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'frontend_react/build')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Then add this also


STATICFILES_DIRS = [

os.path.join(BASE_DIR, 'frontend_react/build/static')

]

Now open the url.py file and add the following lines


from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='index.html')),
]

In the App.Js and edit it to the following

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">

    Hello world

    </div>
  );
}

export default App;

change the directory to frontend_react then run the following

C:\Users\LENOVO\Desktop\django-react\backend_django\frontend_react>npm run build

now go back to the backend_django directory and the run the server using


C:\Users\LENOVO\Desktop\django-react\backend_django>python manage.py runserver

Good Your First project using django and react is done

Check out for the project in github

written by ian