[PYTHON] Beginners try to make an online battle Othello web application with Django + React + Bootstrap (1)

Introduction

Purpose of this page

The purpose is to share the Django + React + Bootstrap web application creation procedure and to make a personal memorandum. As for the content, it will be a form in which beginners will leisurely write down the struggle until implementing Othello of interpersonal battle with Web application with Django + React + Bootstrap through trial and error. I can't explain in detail, so I think it's like going through the steps from environment construction, project creation, UI creation, and Othello implementation.

Target of this page

--Those who want to make a web application. --Somehow someone who can write Python. --Those who have vague knowledge of the front side. --Those who point out mistakes in the content.

environment

item version Supplement
OS Windows 10
Python 3.6.10
Anaconda 4.8.3 It manages the Python environment.
Django 3.0.3 A Python web framework.
numpy 1.18.1 Numerical calculation library for Python. I will put it in because it is convenient.
npm 6.14.4 It is used to install packages such as React.
react 16.9.34 This is the main body of React.
react-dom 16.9.34 It connects Html and React.
react-bootstrap 1.0.1 This is a React implementation version of Bootstrap that makes the design look good.
webpack 4.43.0 It converts React jsx files to js.

table of contents

1st environment construction and project creation

--Build a Django environment with Anaconda. --Create a Django project. --Build a React environment with Node.js. --Use React on your Django project.

** Note: This time, we will only set Django and React, so the implementation of Othello will not come out. ** **

Schedule for the second and subsequent times

--Create the appearance and behavior of Othello with React and Bootstrap. --Manage your account with Django's user management feature. --Build a database for Othello. --Implement Othello's interpersonal battle (online battle) function.

Main subject

1. Build a Django environment with Anaconda

It is assumed that Anaconda is installed. The explanation about installing Anaconda is omitted, so please refer to other pages. After creating an environment called web with the following command, install the necessary ones.

conda create --name web python=3.6.10
conda activate web
conda install django==3.0.3
conda install numpy==1.18.1

2. Create a Django project.

2-1. Creation of the project body

First, create a Django project with the following command. The project will be created directly under the directory where this command is executed. webgame is the name of the project. Anything is fine.

conda activate web
django-admin startproject webgame

I think the project structure looks like this.

webgame --+-- webgame  --+-- __init__.py
          |              +-- settings.py    #This is a Django configuration file. Show the location of Html and set the DB.
          |              +-- urls.py        #URL routing settings.
          |              +-- wsgi.py
          +-- manage.py                     #It manages Django. Start and migrate the DB.

Immediately, type the following command to start it.

cd webgame
python manage.py runserver

After entering the command, access http://127.0.0.1:8000 and if a page like the image below is displayed, it is successful. image.png

2-2. Add page (application)

Next, I will create an index page. As a flow,

  1. Create a home application.
  2. Create an Html file.
  3. Edit the configuration file to make the Html file accessible.
  4. Create a view with the home application.
  5. Set the URL.

I will do it like that.

2-2-1. Create a home application.

You can create a home application with the following command.

python manage.py startapp home

At this stage, the project structure should look like this.

webgame --+-- home     --+-- __init__.py
          |              +-- admin.py
          |              +-- apps.py
          |              +-- models.py      #This is a file that defines a table for a database.
          |              +-- test.py
          |              +-- views.py       #This is the file that creates the behavior of the view.
          +-- webgame  --+-- __init__.py
          |              +-- settings.py    #This is a Django configuration file. Show the location of Html and set the DB.
          |              +-- urls.py        #URL routing settings.
          |              +-- wsgi.py
          +-- manage.py                     #It manages Django. Start and migrate the DB.

2-2-2. Create an Html file

Create a directory as shown below and create ʻindex.html`.

webgame --+-- resources ---- templates ---- home ---- index.html
          +-- home      ----abridgement
          +-- webgame   ----abridgement
          +-- manage.py  

The contents should be as follows.

webgame/resources/templates/home/index.html


<h1>Hello, Django!!</h1>

2-2-3. Edit the configuration file so that you can access the Html file.

Edit settings.py as follows.

webgame/webgame/settings.py (partial excerpt)


//Near line 34
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home',                                                             #add to
]

//Near line 55
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "resources", "templates")            #add to
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

2-2-4. Create a view with the home application.

Edit views.py of the homes application as follows. Now you can read the home / index.html created earlier and pass it as an Http response.

webgame/home/views.py


from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

def index(request):
    template = loader.get_template('home/index.html')
    context = {}
    return HttpResponse(template.render(context, request))

2-2-5. Set the URL.

First, create a new ʻurls.py` in your home application.

webgame --+-- resources ---- templates ---- home ---- index.html
          +-- home      -+--abridgement
          |              +-- urls.py                              #to add
          +-- webgame   ----abridgement
          +-- manage.py  

The contents of ʻurls.py` should be as follows.

webgame/home/urls.py


from django.urls import path
from . import views

app_name = "home"

urlpatterns = [
    path('', views.index, name='index'),
]

In addition, edit webgame / urls.py as follows to read this correctly.

webgame/webgame/urls.py


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

urlpatterns = [
    path('', include('home.urls')),             # home.Set to read urls
    path('admin/', admin.site.urls),
]

If you make this setting and access http://127.0.0.1:8000, you should see the following page. Now you can place your favorite Html file at any URL on your website. image.png

3. Build a React environment with Node.js.

First, install Node.js from https://nodejs.org/ja/. Detailed explanation is left to other pages.

To put React files, add folders and files as follows.

webgame --+-- resources -+-- react     -+-- src ---- home ---- index.jsx #source file
          |              |              +-- package.json                 #Specify what to install.
          |              |              +-- webpack.config.js            #Configuration file when converting from jsx to js
          |              |              +-- .babelrc                     #Magic
          |              +-- templates ----abridgement
          +-- home      ----abridgement
          +-- webgame   ----abridgement
          +-- manage.py  

First, edit package.json as follows.

webgame/resources/react/package.json


{
  "name": "webgame",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "@babel/preset-react": "^7.0.0",
    "@babel/register": "^7.4.0",
    "babel-loader": "^8.0.5",
    "html-webpack-plugin": "^3.2.0",
    "react-bootstrap": "^1.0.1",               # React-Bootstrap (Design related)
    "superagent": "^5.0.2",                    # superagent      (Ajax communication)
    "webpack": "^4.30.0",                      # WebPack         (Create js file)
    "webpack-cli": "^3.3.1",
    "webpack-dev-server": "^3.2.1"
  },
  "dependencies": {
    "react": "^16.13.1",                       # React           (React body)
    "react-dom": "^16.13.1"                    # ReactDOM        (Connect jsx with Html)
  }
}

Next, edit .babelrc as follows.

webgame/resources/react/.babelrc


{
    "presets": [
      "@babel/preset-env", "@babel/preset-react"
    ]
}

Then, install with the following command.

cd resources
cd react
npm install

If all goes well, a folder called node_modules will be created and various libraries will be installed. The folder structure at this time is like this.

webgame --+-- resources -+-- react     -+-- node_modules ----abridgement#This will be added
          |              |              +-- src          ----abridgement
          |              |              +--abridgement
          |              +-- templates ----abridgement
          +-- home      ----abridgement
          +-- webgame   ----abridgement
          +-- manage.py  

This completes the React settings.

4. Use React on your Django project.

Here, we will set and publish according to the following flow.

  1. Create a jsx file
  2. Convert jsx files to js
  3. Read the js file from the Html file
  4. Set to read js files
  5. Start!

4-1. Create a jsx file

First, create a jsx file using React. Edit src / home / index.jsx as follows.

webgame/resources/react/src/home/index.jsx


//Import what you need.
import React from 'react'
import ReactDOM from 'react-dom'

//Create a React component.
class Home extends React.Component {
    constructor() {
        super();
    }

    //Implement the rendered part.
    render() {
        return (
            <h1> Hello, React!! </h1>
        );
    }
}

//Link with Html. here,`home`It is set to associate the tag with the id with the Home component.
ReactDOM.render(
    <Home />,
    document.getElementById('home')
);

4-2. Convert jsx files to js

First, create a storage location for the js file. Please arrange as follows.

webgame --+-- resources -+-- static    ---- js       #Create an empty directory
          |              +-- react     ----abridgement
          |              +-- templates ----abridgement
          +-- home      ----abridgement
          +-- webgame   ----abridgement
          +-- manage.py  

Next, let's edit webpack.config.js as follows.

js:webgame/resources/react/webpack.config.js


require('@babel/register');
const path = require('path');

module.exports = {
    //Set the name and location of the jsx file to load
    entry: {
        home_index:     path.resolve(__dirname, "src/home/index.jsx"),
    },
    //Setting the location and name of the output js file
    output: {
        path: path.resolve(__dirname, "../static/js/") ,
        filename: "[name].js",
    },
    module: {
        rules: [
            {
                test: /\.jsx$/,
                exclude: /node_modules/,
                loader: 'babel-loader'
            }
        ]
    },
    resolve: {
        extensions: [".js","jsx"],
    }
}

After editing, go to webgame / resources / react as shown below and execute webpack. This process is done every time you edit the jsx file.

cd resources
cd react
node_modules\\.bin\\webpack

If webgame / resources / static / js / home_index.js is created with this, it is successful.

4-3. Read js file from Html file

Next, edit the home / index.html file as follows and load the js file.

webgame/resources/templates/home/index.html


<!-- Django3.Read static file at 0-->
{% load static %}

<h1>Hello, Django!!</h1>

<!--Place the tag with id home-->
<div id="home"></div>

<!-- home_index.read js-->
<script src="{% static 'js/home_index.js' %}"></script>

4-4. Set to read js files

Finally, set Django to be able to read static files (js or css). Edit the end of settings.py as follows.

webgame/webgame/settings.py


#Near line 133
STATIC_URL = '/static/'

#Additional part from here
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'resources/static'),
]

4-5. Start!

Let's go back to the hierarchy where manage.py is and start the server as usual.

python manage.py runserver

If you access http://127.0.0.1:8000 and Hello, React !! is displayed, it is successful. image.png

in conclusion

Thank you for reading. It would be very helpful if you could tell me anything that is difficult to understand, something that doesn't work, or something that is wrong.

Next time, I would like to use Bootstrap to create the appearance of Othello, so please continue to support me.

Recommended Posts

Beginners try to make an online battle Othello web application with Django + React + Bootstrap (1)
Let's make an A to B conversion web application with Flask! From scratch ...
(Python) Try to develop a web application using Django
I tried to make an OCR application with PySimpleGUI
[Learning memo] How to make an application with Django ~ Until Hello World is displayed ~
[Learning memo] How to make an application with Django ~ From virtual environment to pushing to github ~
Web application creation with Django
(For beginners) Try creating a simple web API with Django
Try to make a web service-like guy with 3D markup language
Easy-to-understand explanation of Python Web application (Django) even for beginners (5) [Introduction to DB operation with Django shell]
Build a web application with Django
[TCP / IP] After studying, try to make an HTTP client-like with Python
How to build an application from the cloud using the Django web framework
I want to make a web application using React and Python flask
Try to generate an image with aliasing
[For beginners] Try web scraping with Python
I made a WEB application with Django
WEB scraping with python and try to make a word cloud from reviews
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Try to make your own AWS-SDK with bash
AI beginners try to make professional student bots
Try to make a "cryptanalysis" cipher with Python
Try to make a dihedral group with Python
Try to make client FTP fastest with Pythonista
[Cloud9] Try to build an environment with django 1.11 of Python 3.4 without understanding even 1 mm
Procedure for creating an application with Django with Pycharm ~ Preparation ~
Python beginners try adding basic auth to Django admin
Try to make a command standby tool with python
Try to make RESTful API with MVC using Flask 1.0.2
Try running a Django application on an nginx unit
Web application made with Python3.4 + Django (Part.1 Environment construction)
How to make an HTTPS server with Go / Gin
Machine learning beginners try to make a decision tree
Single sign-on to your Django application with AWS SSO
Make an application using tkinter an executable file with cx_freeze
[Python] I tried to make an application that calculates salary according to working hours with tkinter