(十二) Django - views

今天來到MVT的V,views是編寫邏輯的地方,例如定義如何將資料庫的資料呈現在網頁。

Homepage

先簡單的做個首頁。
在內層的mysite下面新增一個views.py,寫下第一個view function:

1
2
3
from django.http import HttpResponse
def homepage(request):
return HttpResponse("Let's get it started.")
  1. 從模組django.http匯入class HttpResponse,它的典型用法是可以在頁面上顯示一串文字。
  2. 新增一組函式,記住每一組函式都要有個HttpRequest的物件作為第一個參數,該物件在Django都會寫成request。
  3. 面對request的提出,網頁自然要給一個response,透過HttpResponse,網頁會回傳指定的字串。

URLS配對views

1
2
3
4
5
6
7
8
# mysite/mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.homepage),
path('quiz/', include('quiz.urls')),]

Template

今天先簡單提一點Template,將首頁加點樣式。
1.首先在外層的mysite下新增一個templates資料夾(跟quiz資料夾要同一層),然後新增一個叫homepage的html檔,內容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# mysite/templates/homepage.html
<html>
<head>
<title>Home page</title>
<style>
body {
background-color: aquamarine;
}
h1,h3{
color: white;
}
</style>
</head>
<body>
<h1>Welcome.</h1>
<h3>{{ now }}</h3>
</body>
</html>

2.function homepage改寫如下:

1
2
3
4
5
from django.shortcuts import renderimport datetime
def homepage(request):
now = datetime.datetime.now() # 現在時間
context = {'now':now}
return render(request, 'homepage.html', context)

3.跑完runserver結果網頁顯示TemplateDoesNotExist,這邊再回settings.py做設定,需要把templates的路徑告訴給Django,這邊更改DIRS的部分即可:

1
2
3
4
5
6
7
8
TEMPLATES = [
{'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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', ],},},]

再runserver一次就可以跑出頁面了,簡單的把背景換個顏色,然後加上時間。
https://ithelp.ithome.com.tw/upload/images/20200913/20129725eNL6NPd2mR.png

小結:views這邊有個學習重點,就是HttpResponse、render跟redirect(之後會大量使用到)的功能跟用法,明天再來看看~晚安