今天來到MVT的V,views是編寫邏輯的地方,例如定義如何將資料庫的資料呈現在網頁。
先簡單的做個首頁。
在內層的mysite下面新增一個views.py,寫下第一個view function:
from django.http import HttpResponse
def homepage(request):
    return HttpResponse("Let's get it started.")
# 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,將首頁加點樣式。
1.首先在外層的mysite下新增一個templates資料夾(跟quiz資料夾要同一層),然後新增一個叫homepage的html檔,內容如下:
# 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改寫如下:
from django.shortcuts import render
import datetime
def homepage(request):
    now = datetime.datetime.now() # 現在時間
    context = {'now':now}
    return render(request, 'homepage.html', context)
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一次就可以跑出頁面了,簡單的把背景換個顏色,然後加上時間。
小結:views這邊有個學習重點,就是HttpResponse、render跟redirect(之後會大量使用到)的功能跟用法,明天再來看看~晚安