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的樣板上

沒有留言:

張貼留言