angoDjango專案加入網路應用程式
加資料庫儲存示範
專案加入網路應用程式(一般常說App是網站上運作的App)
一 建立App的步驟
命令列建立App的指令,建立App就會建立新的套件,也同時會在新的網址執行App程式
第一層demo專案資料夾路徑內終端機
python manage.py startapp encode #新增建立網路應用程式encode
會看到demo專案資料夾路徑新增了encode資料夾
二 建立資料庫相關的models.py及指令
新增models.py的定義,因為App會把網頁得來的資料儲存在資料庫裡,因此要增加models.py裡設定關於資料處理類別的定義
注意models.py是在encode資料夾裡
from django.db import models
class Sentence(models.Models): #定義儲存資料的類別
[tab]original_text=models.ChartField(max_length=200) #original_text為資料庫的欄位 ChartField為文字資料的意思
[tab]encoding_text=models.ChartField(max_length=200) #encoding_text為資料庫的欄位 ChartField為文字資料的意思
def __str__(self):#str()的方法 因此Sentence物件會直接回傳encoding_text的文字資料
[tab]return self.encoding_text
三 建立App後調整相關檔案
(1)調整settings.py的設定(在第二層demo資料夾之中),因為增加了App,因此要在settings.py加入關於App的設定
找到INSTALLED APP=[…]新增
‘encode’, #記得加上逗號
(2)回命令列下達建立資料庫的指令
資料庫設定相關三指令
python manage.py makemigrations encode #替新增的encode App建立資料ai庫模型
python manage.py sqlmigrate encode 0001 #建立encode資料表
python manage.py migrate #實行之前做的所有migrations
(3)設定views.py[encode資料夾中],呈現App執行後的結果
from django.http import HttpResponse
from .encrypt import Encrypt #引入Encrypt類別,*因此待會要把encrypt.py模組加到encode資料夾中
from .models import Sentence #引入models.py的Sentence類別
def result(request): #result()函數顯示編碼的結果
[tab]e=Encrypt()
[tab]s1=”There is no spoon.”
[tab]s2=e.to_encode(s1)
[tab]s=Sentence(original_text=s1,encoding_text=s2)#資料庫處理 建立資料庫模型類別Sentence物件,將參數設定好要儲存的欄位
[tab]s.save() #資料庫處理 save()儲存
[tab][tab]return HttpResponse(“編碼結果為”+s2)
(4)設定urls.py[第二層demo],因為需要新的網址執行App,以及執行App執行後的結果,也就是透過網址執行encode App
from django.contrib import admin
from django.urls import include,path
from . import views
urlpatterns=[
path(‘’,views.now),
path(‘encode/’,include(‘encode.urls’)),#表示切換到encode中的urls.py進行處理
path(‘admin/’,admin.site.urls),
]
繼續要設定[encode資料夾]中的urls.py,從encode資料夾中的urls.py實際呼叫views.py中result()函數
from django import path
from . import views
app_name=’encode’ #設定App name
url_patterns = [
path(‘’,views.result,name=’result’), #’’空字串表示首頁網址加上encode,這個網址會執行views.py中的result()函數
]
最後,要把encrypt模組加到encode資料夾中,即完成