在Visual Studio中集成Django与React的步骤求助
Hey there! I’ve set up Django + React projects in Visual Studio plenty of times, so let me walk you through every detail—from folder structure to package installs and integration. Let’s dive in.
1. First, Make Sure Your Environment is Ready
Before we start, double-check Visual Studio has the tools we need:
- Open Visual Studio, go to Tools > Get Tools and Features
- Ensure the Python Development and Node.js Development workloads are installed (if not, select them and click "Modify" to add)
- Verify your tools work: Open the VS terminal (View > Terminal) and run:
python --version(should show Python 3.8+; newer versions work best)node --version(should show Node.js 14+; React relies on this)
2. Create Your Project Folder Structure
Let’s start with a clean, organized setup:
- Pick a location on your computer and create a main folder, e.g.,
django-react-project - Open this folder in Visual Studio (File > Open > Folder)
- In the VS terminal, create two subfolders:
mkdir backend(for all Django backend code)mkdir frontend(for all React frontend code)
3. Set Up the Django Backend
Let’s build the API layer first. Navigate to the backend folder in the terminal: cd backend
3.1 Create and Activate a Python Virtual Environment
Virtual environments keep your project dependencies isolated—always use them!
- Initialize the venv:
python -m venv venv - Activate it (commands vary by OS):
- Windows (PowerShell):
.\venv\Scripts\Activate.ps1(you might need to enable script execution first viaSet-ExecutionPolicy RemoteSigned -Scope CurrentUser) - Windows (CMD):
.\venv\Scripts\activate.bat - Mac/Linux:
source venv/bin/activate
You’ll see(venv)at the start of your terminal prompt when it’s active.
- Windows (PowerShell):
3.2 Install Django and Required Packages
- Install Django and Django REST Framework (we use this to build APIs easily):
pip install django djangorestframework
3.3 Initialize the Django Project
- Create the core Django project (the
.ensures files go directly intobackend, not a nested folder):django-admin startproject core . - Create an app to hold your API logic:
python manage.py startapp api
3.4 Configure Django Settings
Open backend/core/settings.py in VS, then:
- Find the
INSTALLED_APPSlist and add these lines:'rest_framework', 'api', - Save the file.
3.5 Test the Django Server
- Run database migrations (sets up default Django tables):
python manage.py migrate - Start the development server:
python manage.py runserver
Open your browser and go tohttp://localhost:8000—you should see Django’s default welcome page. Great!
4. Set Up the React Frontend
Now let’s build the UI. Go back to your project root in the terminal: cd .., then navigate to frontend: cd frontend
4.1 Initialize the React Project
- Create a React app directly in the
frontendfolder (the.avoids creating an extra nested folder):npx create-react-app .
This might take a minute—wait for it to finish installing all dependencies.
4.2 Install Axios (For API Calls)
We’ll use Axios to make requests from React to Django’s API:npm install axios
4.3 Test the React Server
- Start the React development server:
npm start
Your browser should open automatically tohttp://localhost:3000, showing React’s default welcome page. Perfect!
5. Connect Django and React
Right now, the two servers run separately—let’s make them talk to each other.
5.1 Allow Cross-Origin Requests in Django
Browsers block cross-domain requests by default, so we need to let Django accept requests from React’s port (3000):
- Go back to the backend terminal (make sure
(venv)is active) and install the CORS package:pip install django-cors-headers - Open
backend/core/settings.pyagain:- Add
corsheaderstoINSTALLED_APPS - In the
MIDDLEWARElist, add this line beforedjango.middleware.common.CommonMiddleware:'corsheaders.middleware.CorsMiddleware', - Add these lines at the bottom of the file:
CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ]
- Add
- Save the file and restart the Django server (stop it with
Ctrl+C, then runpython manage.py runserveragain)
5.2 Test the API Connection
Let’s create a simple API endpoint in Django and call it from React.
Step 1: Create a Django API View
Open backend/api/views.py and replace its content with:
from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def hello_from_django(request): return Response({"message": "Hello from Django! 🚀"})
Step 2: Add a Route for the View
Open backend/core/urls.py and update it to:
from django.contrib import admin from django.urls import path from api.views import hello_from_django urlpatterns = [ path('admin/', admin.site.urls), path('api/hello/', hello_from_django, name='hello'), ]
Step 3: Call the API from React
Open frontend/src/App.js and replace its content with:
import { useEffect, useState } from 'react'; import axios from 'axios'; import './App.css'; function App() { const [message, setMessage] = useState('Loading...'); useEffect(() => { // Call Django's API endpoint axios.get('http://localhost:8000/api/hello/') .then(response => { setMessage(response.data.message); }) .catch(error => { setMessage('Oops, something went wrong!'); console.error('Error fetching data:', error); }); }, []); return ( <div className="App"> <header className="App-header"> <p>{message}</p> </header> </div> ); } export default App;
Now, make sure both Django (port 8000) and React (port 3000) servers are running. Refresh the React page—you should see "Hello from Django! 🚀" displayed. That means your integration works!
6. Optional: Prepare for Production
If you want to deploy the project as a single app (instead of two separate servers), you can build React’s static files and serve them through Django:
- In the frontend terminal, run
npm run build—this creates abuildfolder with optimized static files - Open
backend/core/settings.pyand add these lines (replace existing similar sections if needed):import os # Add React's build folder to static files directories STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build/static'), ] # Add React's build folder to template directories TEMPLATES[0]['DIRS'].append(os.path.join(BASE_DIR, '../frontend/build')) - Update
backend/core/urls.pyto serve React’s main page:from django.views.generic import TemplateView # Add this at the end of urlpatterns urlpatterns += [ path('', TemplateView.as_view(template_name='index.html')), ]
Now, when you run python manage.py runserver, Django will serve React’s frontend at http://localhost:8000, and your API will still work at /api/hello/.
内容的提问来源于stack exchange,提问作者duncan




