2017年4月4日 星期二

Django with React part2

Django with React part2

繼續上一篇django with react環境建立
這次要來建立react所需的檔案

目標

建立react
將其應用到django的templates中

作法

運用npm來安裝所需套件

step1

npm init
此來建立package.json檔,它可以幫我們管理所安裝的套件

step2

npm install --save-dev react react-dom webpack-bundle-tracker babel babel-core babel-loader babel-present-react babel-preset-stage-0
安裝react套件
1. react , react-dom為主要使用的套件
2. babal系列為協助編譯ES6語法
3. webpack-bundle-tracker為此次重點,將react編譯後產生可讓django存取的檔案

step3

npm install -g webpack //可以使用全域安裝webpack,方便後面的編譯
npm install --save-dev webpack@2.1.0-beta.21
安裝所需的webpack,測試時發現使用2.1.0-beta.21此版本才能成功編譯webpack-config.js(後談)之中的resolve屬性,之後再研究有沒有其他版本可以正常使用

step4

mkdir -p assets/js //建立react主目錄
touch webpack-config.js //建立webpack設定檔
touch assets/js/index.js //建立react主js檔

step5

撰寫webpack-config.js檔,基本內容如下
var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    context: __dirname,

    entry: './assets/js/index',

    output: {
        path: path.resolve('./assets/bundles/'),
        filename: '[name]-[hash].js',
    },

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

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

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

step6

撰寫react程式,先寫最基礎的展示看看即可
./assets/js/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';

ReactDOM.render(<App/>, document.getElementById('app'));
./assets/js/app.js
import React, {Component} from 'react';
class App extends Component{
    render(){
        return(
            <h1>Hello React Django</h1>
        );
    }
 }
export default App;
在使用webpack來編譯,如果前面有使用-g來安裝webpack,就可以直接執行下列命令
webpack --config webpack-config.js
也可以執行以下命令
./node_modules/.bin/webpack --config webpack.config.js
到目前為止react部分的設定就完成了,接下來就是要設定django能夠來存取webpack編譯出的檔案

step7

pip install django-webpack-loader
此次另一重點,這是用來讀取webpack的檔案,詳細可觀看django-webpack-loader官方文件

step8

到setting.py做讀取的設定
主要新增以下設定
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

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

INSTALLED_APPS = (
 ...
 'webpack_loader',
)

step9

將template的html做修改
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div id="app"></div>
    {% render_bundle 'main' %}
</body>
</html>

final

最後就可以啟動server,並且依照上一篇設定的路徑http://127.0.0.1:8000/hello/
觀看結果
python manage.py runserver
至此就是django with react的設定

下一目標

  1. 研究React-Hot-Loader來提升開發速度
  2. 研究使用ajax來和後端python做溝通
  3. 研究使用在django使用redux
慢慢把這幾個興趣完成˙ˇ˙

2017年4月3日 星期一

Django with React part1

建立Django專案並結合React

在研究怎麼結合django和react所得到的結果
先將他記錄起來,或許之後能找到更好的做法

所需知識為

  1. python3: 基本的語法
  2. django : python所使用的後端server
  3. react.js : 前端框架
  4. webpack : 用來打包前端的檔案,並可輸出為單一或多個靜態檔
  5. npm : 前端使用的套件管理器

大致作法

  1. 先建立django專案,並使用template
  2. 使用npm安裝react, react-dom, babel…等工具
  3. 使用webpack將react專案打包
  4. 使用webpack-bundle-track產生可讓django讀取的靜態檔案
  5. 使用django-webpack-loader去讀取上一步產生的檔案

首先先建立django專案

假設已安裝好python3並建立虛擬環境
參考 建立python虛擬環境及基本django專案
step1:
建立專案
python django-admin.py startproject mysite
step2:
建立資料庫
python manage.py migrate
step3:
建立APP
python manage.py startapp apptest
step4:
建立templates資料夾
並建立index.html
此時專案目錄應為
├───manage.py
├───db.sqlite3
└───mysite
        settings.py
        urls.py
        wsgi.py
        __init__.py
└───apptest
        __pycache__
        migrations
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        views.py
└───templates
        index.html
step5:
設定django存取templates的html
於settings.py 之中TEMPLATES的 DIRS做存取的設定
TEMPLATES = [
    {
       ...
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/') ],
       ...
    },
]
step6:
建立index.html
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
Hello
</body>
</html>
step7:
於view.py設定存取樣板
from django.shortcuts import render
from datetime import datetime

# Create your views here.

def hello(request):
    return render(request, 'index.html', {
        'current_time': str(datetime.now()),
    })
step8:
設定urls.py讓設定連結
from django.conf.urls import url
from django.contrib import admin
from listTest.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/', hello),
]
final:
啟動server
python manage.py runserver

連結http://127.0.0.1:8000/hello/

成功建立樣板後,之後就可以開始使用webpack來建立react專案並套用在django的樣板上

2017年4月2日 星期日

測試slackEdit

測試使用slackEdit markdown功能

測試目標

  1. 程式碼區塊
  2. 連結google blog

測試1

這是程式碼

def hello():
    print('Hello')

測試2

連結google blog

選擇slackEdit左邊清單publish