Django

tags: Python Django
2021/12/14 By JohnAxer

建置網站步驟

  • 安裝 django 套件
    • pip install django
  • 切換到專案目錄後,新增專案
    • django-admin startproject 專案名稱(<=自己取)
    • 例如: django-admin startproject OneWeb
  • 新增網站應用程式 (每個專案下可以有一到多個應用程式)
    • ./manage.py startapp 應用程式名稱(<=自己取)
    • 例如: ./manage.py startapp One
  • 修改 Project 下 settings.py
    • INSTALLED_APPS 增加 應用程式名稱.apps.應用程式名稱Config
    ​​​​ INSTALLED_APPS = [ ​​​​ 'django.contrib.admin', ​​​​ 'django.contrib.auth', ​​​​ 'django.contrib.contenttypes', ​​​​ 'django.contrib.sessions', ​​​​ 'django.contrib.messages', ​​​​ 'django.contrib.staticfiles', ​​​​ 'One.apps.OneConfig', ​​​​ ] ​​​​ ... ​​​​ Time_Zone = 'Asia/Taipei' ​​​​
  • 網站資料同步
    • ./manage.py migrate
  • 啟動 web 伺服器
    • ./manage.py runserver
  • 設定網站管理員帳號及密碼
    • ./manage.py createsuperuser #建立最高管理員帳號

網站應用程式撰寫

  • 在專案資料夾下,編輯 urls.py

    • 例如:專案資料夾為 OneWeb,請編輯其下的 urls.py
    ​​​​ from django.contrib import admin ​​​​ from django.urls import path ​​​​ from django.urls import include ​​​​ urlpatterns = [ ​​​​ path('one/', include("One.urls")), ​​​​ path('admin/', admin.site.urls) ​​​​ ] ​​​​
    • 新增第6行,讓專案指向應用程式
  • 在應用程式資料夾下,新增檔案 urls.py

    • 例如:應用程式資料夾為 One,請於 One 下新增檔案 urls.py,檔案內容可以複製 Project 資料夾的 urls.py
    ​​​​from django.urls import path ​​​​from . import views ​​​​urlpatterns = [ ​​​​ path('', views.index, name="index"), ​​​​ path('test', views.test, name="test"), ​​​​ path('show', views.show, name="show"), ​​​​] ​​​​
    • Python Django 採用 MTV 架構:
      • Model 資料
      • Template 網頁樣版 (在 MVC 架構下,為 View)
      • View 控制器 (在 MVC 架構下,為 Controller)
    • 第2行,引入應用程式下模組 views (即檔案 views.py)
    • 第5-6行,設定三個網頁,分為對應到不同的 views
  • 在應用程式資料夾下,新增資料夾 templates

    • 目前資料夾結構為
  • 在 templates 資料夾,新增一個 show.html

    ​​​​<!DOCTYPE html> ​​​​<html> ​​​​<head> ​​​​ <meta charset="utf-8"> ​​​​</head> ​​​​<body> ​​​​ {% for item in fruits %} ​​​​ <p> {{ item }} </p> ​​​​ {% endfor %} ​​​​</body> ​​​​</html>
    • 第7-9行,為 Python Django 的網頁樣板語法
  • 撰寫 views.py 對應 urls.py 中的設定

    ​​​​from django.shortcuts import render ​​​​from django.http import HttpResponse ​​​​# Create your views here. ​​​​def index(request): ​​​​ return HttpResponse("Hello, My First Web.") ​​​​def test(request): ​​​​ return HttpResponse("Hello, My First Web. 另外一頁") ​​​​def show(request): ​​​​ s = ["Apple", "Banana", "Lemon", "Grape"] ​​​​ return render(request, 'show.html', {"fruits": s})
    • 第14行的 render 讓 template: show.html 和資料 s (List 串列)結合,產生網頁。
    • 第14行 中的 {"fruits": s} 是一個 dictionary。
  • 驗收成果

參考教學網站