需求
通过访问 http://localhost:8080/timer,能够获取到当前的时间。
实现步骤
第一步:新增templates/home/timer.html,不存在的目录则新建目录
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>当前时间</title>
</head>
<body>
<h1>{{ now }}</h1>
</body>
</html>
第二步:在main/settings.py中配置模板目录
import osBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))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',],},},
]
第三步:在home/views.py中定义视图函数
from django.shortcuts import render
import ztimedef timer(request):context = {"now": ztime.now().format()}return render(request, "home/timer.html", context)
第四步:安装这里用到的ztime依赖
pip install zdppy_ztime-0.1.0.tar.gz
第五步:新增home/urls.py,定义timer对应的路由
from django.urls import path
from . import viewsurlpatterns = [path('timer', views.timer),
]
第六步:修改main/urls.py,挂载home目录下的子路由
from django.contrib import admin
from django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('', include("home.urls")),
]
第七步:启动服务
python manage.py runserver 0.0.0.0:8080
第七步:浏览器访问 http://localhost:8080/timer