建立Django專案並結合React
在研究怎麼結合django和react所得到的結果
先將他記錄起來,或許之後能找到更好的做法
所需知識為
- python3: 基本的語法
- django : python所使用的後端server
- react.js : 前端框架
- webpack : 用來打包前端的檔案,並可輸出為單一或多個靜態檔
- npm : 前端使用的套件管理器
大致作法
- 先建立django專案,並使用template
- 使用npm安裝react, react-dom, babel…等工具
- 使用webpack將react專案打包
- 使用webpack-bundle-track產生可讓django讀取的靜態檔案
- 使用django-webpack-loader去讀取上一步產生的檔案
首先先建立django專案
假設已安裝好python3並建立虛擬環境step1:
參考 建立python虛擬環境及基本django專案
建立專案step2:
python django-admin.py startproject mysite
建立資料庫step3:
python manage.py migrate
建立APPstep4:
python manage.py startapp apptest
建立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的樣板上
沒有留言:
張貼留言