guest@jyi.app:~/blog— bash
--:--:-- KST
$ cat ./posts/30.md
IT 2019.09.29 · 6 min read

Django와 React 연동

Django와 react를 연동한다는 의미

Django는 웹 프레임워크이고, react는 프론트엔드 라이브러리이다. 사용의도의 핵심은 '유지보수'에 있다고 본다.

프로젝트 최종 구조

깊이 3레벨까지만 작성하였다

/django-react /backend /backend /앱이름 /manage.py /frontend /config /node_modules /public /scripts /src package.json yarn.lock

Django & react 설치

선행 과제

  1. 가상환경 활성화 및 django 설치
  2. yarn 설치 $ mkdir django-react $ cd django-react $ django-admin startproject backend $ npx create-react-app frontend

backend

$ pip install django-webpack-loader

django-react/backend/backend/settings.py
...
INSTALLED_APPS = [
...
'webpack_loader',
]
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates"),],
        ...
    }
]
...
WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'bundles/',
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.dev.json'),
    }
}

frontend

cd frontend
yarn add --dev webpack-bundle-tracker
django-react/frontend/config/path.js
...
module.exports = {
...
statsRoot: resolveApp("../backend/")
}
django-react/frontend/config/webpack.config.js
const BundleTracker = require('webpack-bundle-tracker');
...
module.exports = function(webpackEnv) {
  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';

  const publicPath = isEnvProduction
    ? paths.servedPath
    : isEnvDevelopment && 'http://localhost:3000/';  // 이부분을 변경
    ...
    const publicUrl = isEnvProduction
    ? publicPath.slice(0, -1)
    : isEnvDevelopment && 'http://localhost:3000/';  // 이부분을 변경
    ...
    entry: [
    ...
      require.resolve('webpack-dev-server/client') + '?http://localhost:3000',
      require.resolve('webpack/hot/dev-server'),
      isEnvDevelopment &&
        require.resolve('react-dev-utils/webpackHotDevClient'),
      paths.appIndexJs,
    ].filter(Boolean),
    ...
    //맨 아래 plugins에 BundleTracker를 추가
    plugins: [
        ...
        // 이제 yarn start 커맨드 입력 시, django 폴더에 웹팩 번들이 정의된 json파일이 생겨난다.
        new BundleTracker({path: paths.statsRoot, filename: 'webpack-stats.dev.json'}),
    ]
django-react/frontend/config/webpackDevServer.config.js
module.exports = function(proxy, allowedHost) {
  return {
      ...
    host,
    headers: {
      'Access-Control-Allow-Origin': '*'
    },
    ...
  },
}

backend/앱

선행 과제

  1. python manage.py createapp 앱이름
django-react/backend/앱이름/templates/앱이름/index.html
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="root"></div>
{% render_bundle 'main' %}
{% render_bundle 'runtime-main' %}
{% render_bundle 'undefined' %}  // 빈 화면이 뜨는 경우, webpack-stats.devjson 파일을 보고 알맞게 수정해주어야 한다.
</body>
</html>

마치며

해당 템플릿을 views.py와 urls.py에 등록하고, frontend와 backend모두 실행시켜본다. 만일 두 화면이 동일하다면, 개발환경 설정 성공.

참고한 사이트

velog.io: yarn 버전 업에 따라 해당 내용을 최신버전에 맞게 수정했다.

UTF-8  ·  LF ·  정화된 밤 (Verklärte Nacht) Op.4