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
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.
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
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.
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
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
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
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``
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
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 folder
index.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.html
Toajax-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
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
#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