Connect Django with Reactjs
Here are the some step that you guys need to follow to connect django with reactjs.
step:1 create django project (backend) with command django-admin startproject backend.
step:2 create django app inside django project (backend) named blog. with command python manage.py startapp blog
step:3 create reactjs project (frontend) . with command create-react-app frontend.
step:4 In settings.py , Include blog inside in installed app list and install corsheader with command (python -m pip install django-cors-headers) and also include corsheader that allow django project to communicate with reactjs.
INSTALLED_APPS = [
'blog',
'corsheaders',]
step:5 In middleware list of setting.py and add
MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ]
step:6 Here, Include these also in your settings.py
CORS_ORIGIN_ALLOW_ALL=TrueCORS_URLS_REGEX = r'^/api/.*$'
For more detail of corsheadervisit this: https://pypi.org/project/django-cors-headers/
step:7 Now, views.py of blog app which lies inside djangoproject .create function home that response json data.from django.shortcuts import renderfrom django.http import JsonResponse
def home(request): return JsonResponse({'name':'John','address':'xyz','age':45})
CORS_ORIGIN_ALLOW_ALL=True
CORS_URLS_REGEX = r'^/api/.*$'
from django.shortcuts import render
from django.http import JsonResponse
def home(request):
return JsonResponse({'name':'John','address':'xyz','age':45})
step:8 Set the url for django project like this:
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/home/',views.home,name='home')
]
step:9 Django project setup is complete and now we move toward reactjs project frontend. Here is the code
inside app.js :frontend/src/app.js
import React,{useState,useEffect} from 'react';import logo from './logo.svg';import './App.css';
function App() { const [data,setdata]=useState([]); useEffect(()=>{ let url = 'http://127.0.0.1:8000/api/home/'; function loadDoc(url) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { console.log(this.responseText) var value=[JSON.parse(this.responseText)] setdata(value) } }; xhttp.open("GET",url, true); xhttp.send(); } loadDoc(url) } ,[]) return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> {data.map((item,indx)=>{ return(<div key={indx}><li>{item.name}</li><li>{item.age}</li><li>{item.address}</li></div>) })} <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> );}
export default App;
import React,{useState,useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [data,setdata]=useState([]);
useEffect(()=>{
let url = 'http://127.0.0.1:8000/api/home/';
function loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText)
var value=[JSON.parse(this.responseText)]
setdata(value)
}
};
xhttp.open("GET",url, true);
xhttp.send();
}
loadDoc(url)
}
,[])
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{data.map((item,indx)=>{
return(<div key={indx}><li>{item.name}</li><li>{item.age}</li><li>{item.address}</li></div>)
})}
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
0 Comments