但這樣畫面看起來就只有文字
所以要搭配html在瀏覽器上看起來才會比較正常
首先要回到settings.py找到如下
#系統預設
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
#修改成
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],#templete路徑
'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',
],
},
},
]
新增一個templates的資料夾在views.py中寫入function來回傳內容
from django.shortcuts import render
def hello(request):
return render(request, 'hello.html', {"hello_str": "你好啊!!"})
在templates的資料夾中新增一個hello.html內容自訂主要使用h1標籤來看是否有套版
<!DOCTYPE html>
<html>
<head>
<title>您好套版</title>
</head>
<body>
<h1>{{ hello_str }}</h1>
</body>
</html>
urls.py修改
urlpatterns = [
path("hello/",hello),
]
接著瀏覽器輸入http://127.0.0.1:8000/hello
參考來源
Templates · Django Girls 學習指南

