Programing

Django와 ReactJS를 함께 사용하는 방법?

lottogame 2020. 7. 10. 08:17
반응형

Django와 ReactJS를 함께 사용하는 방법?


Django를 처음 사용하고 ReactJS를 처음 사용하십시오. AngularJS와 ReactJS를 살펴 보았지만 ReactJS를 결정했습니다. AngularJS가 시장 점유율을 더 많이 가지고 있음에도 불구하고 AngularJS가 인기를 끌고있는 것처럼 보였으며 ReactJS는 더 빨리 픽업됩니다.

그 쓰레기를 제쳐두고, 나는 Udemy에 대한 코스를 시작했고 몇 개의 비디오 후에 그것이 Django와 얼마나 잘 통합되는지 보는 것이 중요해 보였습니다. 그것은 필연적으로 벽에 부딪쳐서 달려가는 것입니다. 몇 시간과 밤 동안 바퀴를 돌리지 않도록 어떤 종류의 문서가 있습니까?

pip나는 포괄적 인 튜토리얼이나 패키지 가 실제로 없다 . pyreact예를 들어 내가 겪은 몇 가지가 작동하지 않거나 데이트를 했습니다.

한 가지 생각은 ReactJS를 완전히 별개로 취급하는 것이지만 ReactJS 구성 요소를 렌더링하려는 클래스와 ID를 고려하여 별도의 ReactJS 구성 요소를 단일 ES5 파일로 컴파일 한 후 해당 단일 파일을 Django로 가져 오기만하면됩니다. 주형.

Django Rest Framework가 관련이있는 것처럼 들리지만 Django 모델에서 렌더링 할 때 빠르게 고장날 것이라고 생각합니다. Redux 가이 모든 것에 어떻게 영향을 미치는지 알기에는 충분하지 않습니다.

어쨌든 누구나 장고와 ReactJS를 사용하여 공유하는 명확한 방법이 있습니까?

어쨌든 AngularJS와 Django에는 문서와 튜토리얼이 풍부하므로 프론트 엔드 프레임 워크를 시작하기 위해 그 길을 가고 싶어합니다 ... 최고의 이유는 아닙니다.


Django에 대한 경험이 없지만 프론트 엔드에서 백 엔드 및 프론트 엔드 프레임 워크에서 프레임 워크까지의 개념은 동일합니다.

  1. React는 Django REST API를 소비합니다 . 프런트 엔드와 백엔드는 연결되어 있지 않습니다. React는 데이터를 가져오고 설정하기 위해 REST API에 HTTP 요청을합니다.
  2. Webpack (module bundler) & Babel (transpiler) 의 도움으로 Javascript를 단일 또는 여러 파일로 묶어 입력 HTML 페이지에 배치합니다. Webpack, Babel, Javascript 및 React and Redux (상태 컨테이너)를 배우십시오 . 나는 생각 프런트 엔드 렌더링에 반응을 허용하는 대신 장고 템플릿을 사용하지만하지 않습니다.
  3. 이 페이지가 렌더링 될 때 React는 API를 사용하여 데이터를 가져 오므로 React가이를 렌더링 할 수 있습니다. 여기서 HTTP 요청, Javascript (ES6), 약속, 미들웨어 및 반응에 대한 이해 가 필수적입니다.

여기에 웹에서 발견 한 몇 가지 있습니다 한다 (빠른 구글 검색 기준) 도움말 :

이것이 올바른 방향으로 인도되기를 바랍니다! 행운을 빕니다! Django를 전문으로하는 다른 사람들이 내 답변에 추가 할 수 있기를 바랍니다.


Django와 React.js가 함께 작동하기 시작하면서 나는 당신의 고통을 느낍니다. Django 프로젝트를 두 번 수행했는데 React.js는 Django와 잘 어울립니다. 그러나 시작하는 것은 위협적 일 수 있습니다. 우리는 여기 거인의 어깨에 서 있습니다.)

여기에 내가 생각하는 방식이 있습니다. 모두 함께 작동합니다 (큰 그림, 내가 틀렸다면 누군가 나를 수정하십시오).

  • Django와 그 데이터베이스 (Postgres를 선호합니다) 한쪽 (백엔드)
  • 외부 세계에 인터페이스를 제공하는 Django Rest-framework (예 : 모바일 앱 및 반응 등)
  • 반대쪽에있는 Reactjs, Nodejs, Webpack, Redux (또는 아마도 MobX?) (프런트 엔드)

Django와 '프런트 엔드'간의 통신은 Rest 프레임 워크를 통해 이루어집니다. Rest 프레임 워크에 대한 권한 및 권한이 있는지 확인하십시오.

정확히이 시나리오에 적합한 보일러 템플릿을 찾았으며 즉시 사용할 수 있습니다. readme https://github.com/scottwoodall/django-react-template을 따르고 완료되면 Django Reactjs 프로젝트가 실행됩니다. 결코 이것은 생산을위한 것이 아니라, 사물이 어떻게 연결되고 작동 하는지를 파고 볼 수있는 방법입니다!

내가 제안하고 싶은 작은 변화는 이것입니다 : 백엔드를 설정하는 두 번째 단계로 가기 전에 설정 지침을 따르십시오 (Django here https://github.com/scottwoodall/django-react-template/blob/master /backend/README.md ) 설정의 요구 사항 파일을 변경하십시오.

/backend/requirements/common.pip에서 프로젝트의 파일을 찾을 수 있습니다.

appdirs==1.4.0
Django==1.10.5
django-autofixture==0.12.0
django-extensions==1.6.1
django-filter==1.0.1
djangorestframework==3.5.3
psycopg2==2.6.1

이렇게하면 Django 및 Rest 프레임 워크의 최신 안정 버전이 제공됩니다.

도움이 되길 바랍니다.


다른 사람들이 대답했듯이 새 프로젝트를 만드는 경우 프런트 엔드와 백엔드를 분리하고 django rest 플러그인을 사용하여 프론트 엔드 응용 프로그램의 나머지 API를 만들 수 있습니다. 이것은 이상적인 세상에 있습니다.

django 템플릿이 이미있는 프로젝트가있는 경우 응용 프로그램을로드하려는 페이지에 반응 돔 렌더링을로드해야합니다. 필자의 경우 이미 django-pipeline 이 있었고 browserify 확장을 추가했습니다. ( https://github.com/j0hnsmith/django-pipeline-browserify )

예에서와 같이 django-pipeline을 사용하여 앱을로드했습니다.

PIPELINE = {
    # ...
    'javascript':{
        'browserify': {
            'source_filenames' : (
                'js/entry-point.browserify.js',
            ),
            'output_filename': 'js/entry-point.js',
        },
    }
}

" entry-point.browserify.js "는 템플릿에 반응 앱을로드하는 ES6 파일 일 수 있습니다.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.js';
import "babel-polyfill";

import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import reducers from './reducers/index.js';

const createStoreWithMiddleware = applyMiddleware(
  promise
)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App/>
  </Provider>
  , document.getElementById('my-react-app')
);

In your django template, you can now load your app easily:

{% load pipeline %}

{% comment %} 
`browserify` is a PIPELINE key setup in the settings for django 
 pipeline. See the example above
{% endcomment %}

{% javascript 'browserify' %}

{% comment %} 
the app will be loaded here thanks to the entry point you created 
in PIPELINE settings. The key is the `entry-point.browserify.js` 
responsable to inject with ReactDOM.render() you react app in the div 
below
{% endcomment %}
<div id="my-react-app"></div>

The advantage of using django-pipeline is that statics get processed during the collectstatic.


The first approach is building separate Django and React apps. Django will be responsible for serving the API built using Django REST framework and React will consume these APIs using the Axios client or the browser's fetch API. You'll need to have two servers, both in development and production, one for Django(REST API) and the other for React (to serve static files).

The second approach is different the frontend and backend apps will be coupled. Basically you'll use Django to both serve the React frontend and to expose the REST API. So you'll need to integrate React and Webpack with Django, these are the steps that you can follow to do that

First generate your Django project then inside this project directory generate your React application using the React CLI

For Django project install django-webpack-loader with pip:

pip install django-webpack-loader

Next add the app to installed apps and configure it in settings.py by adding the following object

WEBPACK_LOADER = {
    'DEFAULT': {
            'BUNDLE_DIR_NAME': '',
            'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),
        }
}

Then add a Django template that will be used to mount the React application and will be served by Django

{ % load render_bundle from webpack_loader % }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Django + React </title>
  </head>
  <body>
    <div id="root">
     This is where React will be mounted
    </div>
    { % render_bundle 'main' % }
  </body>
</html>

Then add an URL in urls.py to serve this template

from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView

urlpatterns = [

    url(r'^', TemplateView.as_view(template_name="main.html")),

]

If you start both the Django and React servers at this point you'll get a Django error saying the webpack-stats.json doesn't exist. So next you need to make your React application able to generate the stats file.

Go ahead and navigate inside your React app then install webpack-bundle-tracker

npm install webpack-bundle-tracker --save

Then eject your Webpack configuration and go to config/webpack.config.dev.js then add

var BundleTracker  = require('webpack-bundle-tracker');
//...

module.exports = {

    plugins: [
          new BundleTracker({path: "../", filename: 'webpack-stats.json'}),
    ]
}

This add BundleTracker plugin to Webpack and instruct it to generate webpack-stats.json in the parent folder.

Make sure also to do the same in config/webpack.config.prod.js for production.

Now if you re-run your React server the webpack-stats.json will be generated and Django will be able to consume it to find information about the Webpack bundles generated by React dev server.

There are some other things to. You can find more information from this tutorial.


A note for anyone who is coming from a backend or Django based role and trying to work with ReactJS: No one manages to setup ReactJS enviroment successfully in the first try :)

There is a blog from Owais Lone which is available from http://owaislone.org/blog/webpack-plus-reactjs-and-django/ ; however syntax on Webpack configuration is way out of date.

I suggest you follow the steps mentioned in the blog and replace the webpack configuration file with the content below. However if you're new to both Django and React, chew one at a time because of the learning curve you will probably get frustrated.

var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    context: __dirname,
    entry: './static/assets/js/index',
    output: {
        path: path.resolve('./static/assets/bundles/'),
        filename: '[name]-[hash].js'
    },
    plugins: [
        new BundleTracker({filename: './webpack-stats.json'})
    ],

 module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },


  resolve: {
        modules: ['node_modules', 'bower_components'],
        extensions: ['.js', '.jsx']
    }
};

The accepted answer lead me to believe that decoupling Django backend and React Frontend is the right way to go no matter what. In fact there are approaches in which React and Django are coupled, which may be better suited in particular situations.

This tutorial well explains this. In particular:

I see the following patterns (which are common to almost every web framework):

-React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium)

-Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication)

-Mix and match: mini React apps inside Django templates (difficulty: simple)


You can try the following tutorial, it may help you to move forward:

Serving React and Django together


I know this is a couple of years late, but I'm putting it out there for the next person on this journey.

GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.

You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.

참고URL : https://stackoverflow.com/questions/41867055/how-to-get-django-and-reactjs-to-work-together

반응형