2021年11月18日 星期四

Python Django Template(6)

承上篇路徑跟view已經可以搭配了
但這樣畫面看起來就只有文字
所以要搭配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 學習指南

Python Django urls .py and views.py(5)

這次練習urls.py
urls.py可指定目前所有連結但需配合著views.py(可自取名字)來顯示
在website資料夾下建立一個views.py
在view.py中寫入function來回傳內容
from django.http import HttpResponse
def home(request):
      return HttpResponse("yes this is your home success!")
接著修改urls.py內容
#原本
from django.contrib import admin
from django.urls import path
urlpatterns = [
     path("admin/", admin.site.urls),
]
#修改後
from django.contrib import admin
from django.urls import path
from website.views import home #要import進來
urlpatterns = [
    #path("admin/", admin.site.urls),
    path("homexx/", home), #(網頁路徑,function)
]
接著瀏覽器輸入
http://127.0.0.1:8000/homexx/
更進階一點views.py加入
def yourinfo(request,name, age):
    return HttpResponse("您的名字{name},您的年齡{age}".format(name = name ,age = age))
修改urls.py
from website.views import home,yourinfo #要import進來
urlpatterns = [
    path("homexx/", home), 
    path("yourinfo/<str:name>/<int:age>",yourinfo),
]
接著瀏覽器輸入
http://127.0.0.1:8000/yourinfo/陳00/35

Python Django settings.py(4)

承上篇建置Django網站後會產生幾個檔
本篇大約簡單說明settings.py裡幾個比較常會使改到的
更進階後面會依文章需求補上
#這個開發時可True,正式發布時請一定要改False
DEBUG = True
#預設語言為en-us
#後期版本已經沒有zh-TW了請使用zh-hant(漢字繁體) or zh-hans(漢字簡體)
LANGUAGE_CODE = 'zh-hant'
多國語言可參考Using Language Identifiers (RFC 3066)
#系統時區預設UTC
TIME_ZONE = 'Asia/Taipei'
時區可參考List of tz database time zones