New project (django_react)
New project (django_react)
project:
---
```bash
# Create a project folder
mkdir myproject && cd myproject
* In `backend/settings.py`:
```python
INSTALLED_APPS = [
...
'rest_framework',
'corsheaders',
'api',
]
```
```python
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ALLOW_ALL_ORIGINS = True # Or configure specifically for React
```
* In `api/urls.py`:
```python
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello_world),
]
```
* In `backend/urls.py`:
```python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
```
```bash
python manage.py migrate
python manage.py runserver
```
---
```bash
npx create-react-app frontend
cd frontend
```
```bash
npm install axios react-router-dom
```
In `src/App.js`:
```js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/hello/')
.then(res => setMessage(res.data.message))
.catch(err => console.error(err));
}, []);
return (
<div>
<h1>Django + React</h1>
<p>{message}</p>
</div>
);
}
---
In `frontend/package.json`, add:
```json
"proxy": "http://127.0.0.1:8000",
```
---
```
myproject/
│
├── backend/
│ ├── backend/
│ └── api/
│
└── frontend/
```