React → Ajax → Django on Linux implementation memo

background

  1. I want to combine React and Django
  2. Find out how to do it ⇒ Play with the virtual environment ⇒ Instant death
  3. Build two development servers ⇒ Don't you build? ⇒ Impossible
  4. Should I put the built React into Django?

When I tried it, it was very troublesome and very unusable. Because I was very demented to forget how to use Django I will write it here as a memorandum Maybe the same as others do I'm a weak programming person

methodology

Unify virtual servers (simple) The goal is to bring implementation 1 to the state of implementation 2. Because it is an unco environment that requires build in implementation 2 and development Explore the procedure to create implementation 1 and bring it to implementation 2. image.png

Probably the correct answer is sand's literature [1]. The weakness that couldn't do that is taking a gorilla method like this one Looking back at his article, I don't understand webpack (Kas) Probably this time, if it is limited to implementation 2 of the final goal, do not npm / pip except react and django

For the environment, the web application course of N Preparatory School is used as it is. I'm building Linux on Windows 10 with Vagrant

Implementation 1

Build and communicate development servers with both React and Django

React

First move tmux and first make a React app I named it ajax-js

create-react-app ajax-js

Go inside the folder and delete the initial file in src

cd ajax-js
rm -rf src/*

Create index.js in the folder

index.js has a server URL variable and sends it there The class (component?) Has a string as a state Initially "React", but if it succeeds in communicating with the server, it becomes "Django"

src/index.js


import React from "react";
import ReactDOM from "react-dom";

const SERVER = "http://127.0.0.1:8000/ajax/"; //Server post

class Ajax extends React.Component {
  constructor(props) {
    console.log(props);
    super(props);
    this.state = {
      message: props.message
    };
  }

  /**
   *Get CSRF tokens from cookies
   */
  getCSRFtoken() {
    for (let c of document.cookie.split(";")) { //Take out one by one
      let cArray = c.split("="); //further=Divide with and into an array
      if (cArray[0] === "csrftoken")
        return cArray[1]; //If it matches the key you want to retrieve
    }
  }

  /**
   *Send data to the server
   */
  submitData() {
    console.log("Send", this.state);
    fetch(SERVER + "res/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": this.getCSRFtoken()  //CSRF token
      },
      body: JSON.stringify({
        message: this.state.message   //Status
      })
    })
      .then((res) => res.json())
      .then((res) => {
        console.log("Receive", res);
        this.setState({ message: res.message });
        this.render();
      });
  }

  /**
   *Button and send / receive data rendering
   */
  render() {
    return (
      <div>
        <div className="submit-element">
            <button onClick={() => this.submitData()}>Submit</button>
        </div>
        <div className="message-element">
            <span className="message-text">{this.state.message}</span>
        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <React.StrictMode>
    <Ajax message={"React"} />
  </React.StrictMode>,
  document.getElementById("root")
);

~~ I remember doing something like {% CRSF_token%} with a Django template. The template seems to have a token in the cookie ~~ You're a lie It seems that if you put {% csrf_token%} in the template, the token will be set in the cookie. image.png Hmm ... So take [2]

Pattern 1


  getCSRFtoken() {
    for (let c of document.cookie.split(";")) { //Take out one by one
      let cArray = c.split("="); //further=Divide with and into an array
      if (cArray[0] === "csrftoken")
        return cArray[1]; //If it matches the key you want to retrieve
    }
  }

So send it to the feature header However, this chapter disables CSRF measures on the Django side, so it is meaningless here. Related to the next chapter (maybe)

  submitData() {
    console.log("Send", this.state);
    fetch(SERVER + "res/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": this.getCSRFtoken()  //CSRF token
      },
      body: JSON.stringify({
        message: this.state.message   //Status
      })
    })

Check the result on the development server npm start (slow cusso) or codes andbox (fast cusso) Since communication with the server can only be done with the development server, make it with codes andbox and put it in the development server when completed

Build is npm run-script build This is also slow and I want to stop programming

image.png

While the sloppy button and React are displayed and I want to die Start the development server and hit tmux to move to the next

Django It's a hassle

Python virtual environment

Create an ajax-python (appropriate) environment with venv

python3 -m venv ajax-python

If you use venv in a virtual environment in Windows, you can not execute it depending on the authority of the prompt shell you started, so reopen shell as an administrator Terminal is probably unnecessary (Mac is God.)

Move and enter the environment

cd ajax-python
source bin/activate

Put Django in pip django-cors-headers can be later

pip install django django-cors-headers
django-admin startproject mysite

Build an ajax app and migrate like a spell

python manage.py startapp ajax
python manage.py migrate

ajax app

From this point on, it's bothersome and bald

urls

Create new urls in ajax app I will return some json to the user when a res request comes

ajax/urls.py


from django.urls import path

from . import views

app_name = 'urls'
urlpatterns = [
	path('', views.Index, name='index'),
    path('res/', views.Res, name='res'),
]

views Appropriate in the view Only display the inside of the request on the console For the time being, return the message "Django"

ajax/views.py


from django.shortcuts import render
from django.http.response import JsonResponse

def Index(request):
	"""
Display the page created by React
	"""
	return render(request, 'ajax/index.html')

def Res(request):
	"""
	"Django"Returns
	"""
	data = request.body.decode('utf-8')
	print("Receive", data)
	response = JsonResponse({
	    "message": "Django",
	})
	return response

mysite

Next, register the ajax app on mysite

setting

Development server Two stages will cross-site with React and Django Then React will not receive the CRSF token generated by Django with the first cookie and will die instantly Therefore, governance is governed [3]

mysite/setting.py


ALLOWED_HOSTS = ["127.0.0.1"]
CORS_ORIGIN_ALLOW_ALL = True # TODO: Cross-Origin

Add ajax app Also add corsheaders for CS measures

mysite/setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ajax.apps.AjaxConfig', #Newly made app
    'corsheaders', # TODO: Cross-Origin
]

In addition, turn off Django's CSRF measures Put Cors Middleware

mysite/setting.py


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware', # TODO: add before
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware', # TODO: Cross-Origin
]

urls Pass the ajax app path to mysite

mysite/setting.py


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('ajax/', include('ajax.urls')),
]

Import ```include``

Brief Summary

The result is the same as the result in the next chapter, so it is omitted. Up to this point, both kindergarten children and dirty people can do it. The problem is that you can't use this on the server, right? Investigate the alternative solution I was overwhelmed by the height of awareness that Docker had already been distributed. Next, try to solve with the power system Ikenuma move

Implementation 2

Tweak the contents of the built React into a Django template

React ⇒ Django

First build by moving tmux to npm

npm run-script build

Thenreact-js/build```In the folderindex.html``And other file folders are generated This index.The html contains the path of the js file I'm not sure how to handle it with Django. Index for the time being.html is Django templates Put others in static

Create a templates folder and a static directory in your app ajax-js/build/index.htmlToajax-py/mysite/ajax/templates/ajax/Copy to ajax-js/build/Folder inajax-py/mysite/ajax/static/ajax/Copy to

"/To"{% static 'ajax/' %}/Replace with This is in short

<script src="/static/js/2.f563a5c7.chunk.js"></script>

To

<script src="{% static 'ajax/' %}/static/js/2.f563a5c7.chunk.js"></script>

Want to be like Now that the path has passed from the template to the mystery js At the beginning{% csrf_token %}When{% load static %}Insert to load the template and set the CSRF token to a cookie

index.html


{% csrf_token %}
{% load static %}
<!doctype html>
...

This completes the static loading

Now start the Django serverhttp://127.0.0.1:8000/ajax/To access When the page is loaded and the button is pressed, if the characters on the screen become Django, it ends

Django

Finally, disable the CORS related that was enabled in the previous chapter. Check if it works with disabled middleware enabled

mysite/setting.py


ALLOWED_HOSTS = ["127.0.0.1"]
 CORS_ORIGIN_ALLOW_ALL = True # TODO: Cross-Origin

mysite/setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
 'ajax.apps.AjaxConfig', # Newly created app
    # 'corsheaders', # TODO: Cross-Origin
]

mysite/setting.py


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware', # TODO: add before
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'corsheaders.middleware.CorsMiddleware', # TODO: Cross-Origin
]

##result image.png

#Conclusion Die

#reference [1]@sand, Create a Django page with React- Webpack4,December 21, 2019. [2]@dokkoisho, Cookie operation with javascript,May 22, 2019. [3]@MuuKojima, Django REST Framework : Cros-Origin settings,November 10, 2017.

Recommended Posts

React → Ajax → Django on Linux implementation memo
NTP configuration memo on Linux
Try Ajax on the Django page
[Note] Run Django on Amazon Linux 2
Like button implementation in Django + Ajax
Django blog on heroku: login implementation
Linux x memo
Django Learning Memo
linux (ubuntu) memo
django tutorial memo
Linux # Command Memo 1
Publish your Django app on Amazon Linux + Apache + mod_wsgi
Memo of deploying Django × Postgresql on Docker to Heroku
A memo when Django was released on VPS (preparation)
Daemonizing processes on Linux
Django drop-down menu implementation
jblas on Arch Linux
Linux standard textbook memo 1
Linux standard textbook memo 3
Linux (WSL) on Windows
NAT router on Linux
[For memo] Linux Part 2
Celery notes on Django
Django memo # 1 from scratch
Run Django on PythonAnywhere
Develop .NET on Linux
Wake on lan on Linux
Hello World on Django
Monitor traffic on Linux
Update vscode on linux
Try NeosVR on Linux
Check capacity on Linux
[Memo] Django development environment
LiveUSB creation on Linux
Linux operation on Win10
A memo on how to easily prepare a Linux exercise environment
Memo of Linux environment construction using VirtualBox + Vagrant on Windows 10