搭建 react 和 django(使用 django-rest-framework)的开发环境
此文章的内容简要
本文将介绍React×Django(django-rest-framework)环境的配置。
在搭建React×Django环境之前的工作
搭建React开发环境
Django的环境设置
Django REST Framework的安装和配置方法。
搭建React和Django的环境
// Django環境作成(バックエンド)
$ mkdir backend
$ cd backend
$ django-admin startproject config .
$ python3 manage.py startapp app
$ python3 manage.py migrate
$ python3 manage.py runserver
// react環境作成(フロントエンド)
$ mkdir frontend
$ cd frontend
$ npx create-react-app .
$ npm install axios # axioxのインストール
使用React和Django进行配置和应用开发。
Django的开发(后端)
config的设置
INSTALLED_APPS = [
'rest_framework', # 追加
'corsheaders', # 追加
'api', #追加
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # 追加
'django.middleware.common.CommonMiddleware', # 追加
]
REST_FRAMEWORK = { # 追加
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
CORS_ORIGIN_WHITELIST = ( # 追加
'http://localhost:3000',
)
from django.contrib import admin
from django.urls import path, include # 追加
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')), # 追加
path('api/', include('api.urls')), # 追加
]
建立模型
from django.db import models
from django.utils import timezone # timezoneのインポート
class Food(models.Model):
name = models.CharField(verbose_name='食材名', max_length=40)
content = models.TextField(verbose_name='食材説明', max_length=400, blank=True, null=True)
created_at = models.DateTimeField(verbose_name='作成日時', default=timezone.now)
updated_at = models.DateTimeField(verbose_name='編集日時', blank=True, null=True)
def __str__(self):
return self.name
创建序列化器
from rest_framework import serializers
from .models import Food
class FoodSerializer(serializers.ModelSerializer):
created_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True)
updated_at = serializers.DateTimeField(format="%Y-%m-%d %H:%M", read_only=True)
class Meta:
model = Food
fields = '__all__'
使用视图集创建视图。
from rest_framework import viewsets
from .models import Food
from .serializers import FoodSerializer
class FoodViewSet(viewsets.ModelViewSet):
queryset = Food.objects.all()
serializer_class = FoodSerializer
创建URLs
from django.urls import path, include
from rest_framework import routers
from .views import FoodViewSet
foodRouter = routers.DefaultRouter()
foodRouter.register('food', FoodViewSet)
urlpatterns = [
path('', include(foodRouter.urls)),
]
用React创建(前端)
App.js的设置
import FoodList from "./components/FoodList";
function App() {
return (
<>
<FoodList />
</>
);
}
export default App;
FoodList.js的设置
import { useState, useEffect } from 'react';
import axios from 'axios';
const FoodList = () => {
const initState = {
id: '',
name: '',
content: '',
}
const [list, setList] = useState(initState);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get(`http://localhost:8000/api/food/`)
.then((res) => {
setList(res.data);
setLoading(false);
})
.catch((err) => {
throw new Error(err)
})
.finally(() => {
})
}, [])
return (
<>
<h1>foodlist</h1>
{
loading?
<h1>...Loading</h1>
:
<>
{list.map(f => <p key={f.id}>{f.name}</p>)}
</>
}
</>
)
}
export default FoodList;