close

Python Django 學習紀錄(二) 建立專案

 

 

一、建置Django專案:

Django套件安裝完成後

即可建立Django專案

語法如下:

django-admin startproject 專案名稱

例如建立一個名為「firstproject」專案

接著將目錄切換到firstproject,這個動作就是進入firstproject專案

3.JPG

4.JPG

 

這邊使用tree指令建立一個樹狀目錄方便大家觀看

tree E:\Django\DjandoEnv\firstproject /f >tree.txt
// /f為顯示文件夾每個文件的名稱,並以tree.txt將目錄存下來

 

打開文件可以看到當前專案結構如下:

列出資料夾 PATH
磁碟區序號為 0000000F C8A7:08DB
E:\DJANGO\DJANGOENV\FIRSTPROJECT   //本專案的目錄(上層)
│  manage.py                     //Python命令檔,提供專案管理的功能,包含建立app、啟動Server和Shell等
│  tree.txt                      //剛剛創建的樹狀目錄文件
│  
└─firstproject                   //包含專案設定、url配置、網頁伺服器介面設定檔(下層)
        settings.py            //本專案的設定檔
        urls.py                //url配置檔
        wsgi.py                //網頁伺服器和Django的介面設定檔
        __init__.py            //一個空檔,使得該目錄(下層firstproject)成為一個Python package

        

二、建立應用程式與目錄

1.建立Application應用程式:

Application應用程式相當於Project專案的元件,簡稱為app。

每個Project專案可以建立一個或多個Application應用程式

語法如下:

python manage.py startapp 應用程式名稱

例如建立 myapp 應用程式

python manage.py startapp myapp

5.JPG

6.JPG

 

2.建立templates目錄:

Django是使用MTV架構,將顯示的模板(.html檔)放置在templates目錄中,因此必須在最上層目錄下建立templates目錄

md templates

 

3.建立static目錄:

Django會將使用的圖形檔,CSS、或Javascript檔案,除了以url方式儲存在網站上,也常以本機方式儲存在static目錄中,因此必須再專案的最上層目錄建立static目錄作為本機儲存的路徑

md static

 

4.建立migration資料檔:

Django要使用資料庫,通常會將建立資料表的架構和版本記錄下來,以利以後的追蹤

python manage.py makemigrations [應用程式]

例如對myapp進行makemigrations

python manage.py makemigrations myapp

若省略[應用程式]參數,將會對所有專案的app進行makemigrations,並且會在應用程式目錄產生migrations目錄

 

5.模型與資料庫同步:

利用migrate可以根據migration的記錄,將模型同步到資料庫。

python manage.py migrate [應用程式]

若省略[應用程式]參數,將會對所有專案的app進行migrate,例如對所有的app進行migrate

python manage.py migrate

7.JPG

 

6.啟動Server:

以manage.py 即可啟動server

python manage.py runserver

8.JPG

之後打開瀏覽器,在網址列打上http://127.0.0.1:8000/

9.JPG

 

 

三、啟動已經建立的專案

如果專案已經建立,想重新開啟該專案可以依照以下步驟

1.切換目錄到Django目錄

cd /d E:\Django\DjangoEnv

 

2.啟動該虛擬環境

Scripts\activate

 

3.進入firstproject專案

cd firstproject

 

4.以manage.py即可啟動伺服器

python manage.py runserver

 

 

 

四、環境設定

<settings.py>是整個專案的環境設定檔,新建的專案都必須先做設定,請打開<setting.py>檔案


1.除錯模式設定

第26列 DEBUG=True 預設為除錯模式,執行時若出現錯誤訊息方便除錯,真正上線部署請將True改為False增加網站的安全

DEBUG = True

 

2.加入Application應用程式

在INSTALLED_APPS中有多需多預設加入的APP,請將自己建立的myapp加入到INSTALLED_APPS串列中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp', #新增的app
]

 

3.設定Template路徑

Django使用MTV架構(後面將會說明),會將顯示的模板放置在Template中,因此必須在TEMPLATE與DIR之間設定其路徑,BASE_DIR是專案的最上層目錄(本例為firstproject)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], #加上template路徑
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },

 

 

4.設定語系和時區

預設為英文語系,請改為中文語系、台北時區

LANGUAGE_CODE = 'zh-Hant' #改為繁體中文

TIME_ZONE = 'Asia/Taipei' #改為台北時區

 

5.設定static靜態擋路徑

static目錄儲存本機中的圖形檔、CSS、或JavaScript檔案,因此必須加入STATICFILES_DIRS並設定其路徑

STATIC_URL = '/static/'
STATICFILES_DIRS = [                      #加入static路徑
  os.path.join(BASE_DIR, 'static'),
]

 

 

五、視圖(view)與URL

Django的程式是採用urlpattern網址和函式對照方式,有兩個步驟:

  • 設定 <urls.py>檔urlpattrens串列中 url 網址和函式的對照
  • 在 <view.py>中撰寫函式

1.設定urls.py

開啟第二層firstproject目錄下的 <urls.py>

from django.contrib import admin
from django.urls import path

from django.conf.urls import url  #導入url套件
from myapp.views import sayhello  #導入sayhello自訂函數

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',sayhello),          #r'^$'為正規表達式起始(^)與結束($)
]

之後瀏覽127.0.0.1:8000時將會執行sayhello函式(將在下面解說)

2.定義函式

所有函式都定義在myapp應用程式中的 <views.py>檔中,請開啟該檔並自訂一個名為sayhello的函式

from django.http import HttpResponse     #導入HttpResponse套件
def sayhello(request):                   #參數為request

    return HttpResponse("Hello Django!")

 

3.瀏覽網頁

上述步驟完成後,瀏覽 127.0.0.1:8000將會為如下的畫面:

11.JPG

4.不同網址執行相同的網頁

不同的網址也可以執行相同的函式,舉例增加一個網址路徑為 127.0.0.1:8000/hello/ ,然後將執行sayhello函式

此時則需要再firstproject\urls.py 中再加入一條程式碼

from django.contrib import admin
from django.urls import path

from django.conf.urls import url  #導入url套件
from myapp.views import sayhello  #導入sayhello自訂函數 ㄆ

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',sayhello),          #r'^$'為正規表達式起始(^)與結束($)
    url(r'^hello/$',sayhello),    #在$前加上/代表網址結束前必須有個/符號
]

12.JPG

 

5.傳送參數

網址也可以直接傳送參數,例如瀏覽 「127.0.0.1:8000/hello2/生番 」這個網址會顯示「Hello 生番」,也就是要傳送的參數為"生番"。

打開myapp\views.py 自訂新的函數

def hello2(request,username):
    return HttpResponse("Hello " + username)

打開firstproject\urls.py 宣告新的自訂函數、新增hellopotato網址路徑與傳送的參數

from django.contrib import admin
from django.urls import path

from django.conf.urls import url  #導入url套件
from myapp.views import sayhello,hello2  #導入sayhello、hello2自訂函數


urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',sayhello),          #r'^$'為正規表達式起始(^)與結束($)
    url(r'^hello/$',sayhello),    #在$前加上/代表網址結束前必須有個/符號
    url(r'^hello2/(\w+)/$',hello2),    #(\w+)表示包含一個以上的字元,因此都會執行hello2的自訂函式
]

13.JPG

 

6.模板的使用

前面的範例使用HttpResponse函式顯示網頁內容,接下來改用模板的方式,將顯示的內容放在.html檔案中

請在templates目錄中新增 <hello3.html>,內容為:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>第一個模板</title>
</head>
<body>
    <h1>歡迎光臨: {{username}}</h1>
    <h2>{{now}}</h2>
</body>
</html>

 

其中模板讀取變數的語法為:

{{變數}}

定義名為hello3的url來執行hello3自訂函式:

from myapp.views import sayhello,hello2,hello3,hello4
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',sayhello),          #r'^$'為正規表達式起始(^)與結束($)
    url(r'^hello/$',sayhello),    #在$前加上/代表網址結束前必須有個/符號
    url(r'^hello2/(\w+)/$',hello2),    #(\w+)表示包含一個以上的字元,因此都會執行hello2的自訂函式
    url(r'^hello3/(\w+)/$',hello3),      #hello3自訂函式
]

定義hello3的自訂函式。以username接收參數,以render函式呼叫模板,同時將參數傳給<hello3.html>模板:

from django.shortcuts import render  #導入render套件
from datetime import datetime        #導入datatime套件,取得現在的日期時間

def hello3(request,username):
    now = datetime.now()             #取得現在日期時間
    return render(request,"hello3.html",locals())  #render(request傳遞GET或POST,模板名稱,傳遞所有區域變數)

 

7.加入static靜態檔案

網站中的圖形檔、CSS、JavaScript以網站內儲存的方式稱為靜態檔案。這些檔案會存在static目錄中,也可以在該目錄中在建立子目錄(images、css、javascript)來分別管理

在<setting.py>中宣告還不夠,在.html中還要再以 {% load staticfiles %} 宣告使用靜態檔案、以 {% static 靜態檔案 %}  格式設定靜態檔案路徑,以下將舉例:

首先在static目錄中新增一個名為images的子目錄,將potato.jpg放入其中。再來新增一個名為css的子目錄,將<style.css>放入其中。

接著定義url,記得要import之後的自訂函數名稱

from myapp.views import sayhello,hello2,hello3,hello4
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$',sayhello),          #r'^$'為正規表達式起始(^)與結束($)
    url(r'^hello/$',sayhello),    #在$前加上/代表網址結束前必須有個/符號
    url(r'^hello2/(\w+)/$',hello2),    #(\w+)表示包含一個以上的字元,因此都會執行hello2的自訂函式
    url(r'^hello3/(\w+)/$',hello3),
    url(r'^hello4/(\w+)/$',hello4),
]

定義hello4自訂函數。以username接收參數,以render函式呼叫模板,同時將參數傳給<hello4.html>模板:

def hello4(request,username):
    now = datetime.now()             #取得現在日期時間
    return render(request,"hello4.html",locals())  #render(request傳遞GET或POST,模板名稱,傳遞所有區域變數)

 

在templates目錄新增hello4.html,內容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>顯示圖片的模板</title>
    {% load staticfiles %}
    <link href = "{% static "css/style.css" %}" rel="stylesheet" type="text/css"/>
</head>
<body>
  <div id="home">
      <img src="{% static "images/potato.jpg" %}" alt="歡迎光臨" width="32" height="32" />
    <span class = "info">歡迎光臨: {{username}}</span>
    <h2>{{now}}</h2>
    </div>
</body>
</html>

 

<style.css>定義info類別樣式如下:

.info{
  color:red;
  font-size:1.5em;
}

完成後執行結果如下圖:

14.JPG

 

 

 

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 ivankao 的頭像
    ivankao

    IvanKao的部落格

    ivankao 發表在 痞客邦 留言(1) 人氣()