Python網頁設計-Django使用筆記(七):套用Bootstrap Template
Django系列文:
Python網頁設計-Django使用筆記(二):實作104職缺爬蟲APP
Python網頁設計-Django使用筆記(三):Mezzanine CMS
Python網頁設計-Django使用筆記(四):LINE聊天機器人(部署至Heroku)
Python網頁設計-Django使用筆記(五):資料庫(CRUD)
本文將帶領讀者快速套用現成的Bootstrap的模板到Django中
mkdir django-bootstrap-dashboard #建立資料夾
cd django-bootstrap-dashboard #移動到資料夾中django-admin startproject dashboard #建立dashboard專案
cd dashboard #移動到專案資料夾中python manage.py startapp APP #建立一個名為APP的Django APPmd templates #建立templates資料夾(放HTML)
md static #建立static資料夾(放HTML,CSS,JS)python manage.py makemigrations #建立資料庫檔案
python manage.py migrate #同步模型與資料庫python manage.py runserver #啟動Server
#預設網址:http://127.0.0.1:8000/修改settings.py,加入Application應用程式
INSTALLED_APPS中加入我們的APP名稱,此例為APP修改settings.py,設定TEMPLATES路徑
修改'DIRS'部分,如下所示:
'DIRS': [os.path.join(BASE_DIR, 'templates'),],修改settings.py,設定static路徑
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]複製static和templates檔案
[1]把開發好或寫好的Bootstrap模板複製到static資料夾,把html檔案複製到template資料夾裡面。[2]注意,需要修改HTML裡面的CSS和JS路径,例如在template資料夾底下,我想要連回static資料夾中的css,則可以改成:<link rel=”stylesheet” href=”../static/assets/css/bootstrap-4.4.1-dist/css/bootstrap.min.css”/>修改views.py,渲染出HTML網站
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loaderdef index(request):
return render(request,'index.html')修改urls.py,建立Routing
from django.contrib import admin
from django.urls import path
from APP.views import index #從上個步驟的views.py引入index函數#當進入http://127.0.0.1:8000/index/後,執行index函數,開啟index.htmlurlpatterns = [
path('admin/', admin.site.urls),
path('index/', index),
]