tortoise512

1. 用户访问 http://127.0.0.1:8000/timer/ 可以看到路径为timer/。

2. timer/路径将对应主项目下urls.py中的timer/。

from app01 import views
urlpatterns = [
    path(\'admin/\', admin.site.urls),
    path("timer/", views.get_timer),
    path("login/", views.login),
    path("auth", views.auth)
]

可以看到timer/路径对应的是app01下的views下的get_timer函数。

3. 找到app01下的views.py文件,如下:

from django.shortcuts import render
import datetime
# Create your views here.

def get_timer(request):
    current_timer = datetime.datetime.now().strftime("%Y-%m-%d %X")
    return render(request,"timer.html",{"nowstr": current_timer})

可以看到返回的是一个timer.html,同时将该html文件中的变量nowstr替换为current_timer。

4. 找到对应的timer.html,这里我们注意到代码中没有跟路径,说明这个文件在默认路径下,Django的默认路径在setting.py中设置。如下:

import os
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\',
            ],
        },
    },
]

这里需要先import os,然后在将templates文件夹指定为模板文件的存放位置。

5. 打开templates文件夹找到timer.html,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timer</title>
    <style>
        span {
            color: red;  /*颜色变红*/
        }
    </style>
</head>
<body>
<H3>当前时间 <span>{{ nowstr }}</span></H3>
</body>
</html>

可以看到里面span标签有个变量叫nowstr,在该变量将被替换为当前时间,并渲染为红色之后,将页面整体返回给用户侧。

分类:

技术点:

相关文章:

  • 2021-12-07
  • 2021-11-16
  • 2021-06-26
  • 2021-12-26
  • 2021-06-11
  • 2022-12-23
  • 2021-05-06
  • 2022-12-23
猜你喜欢
  • 2021-11-16
  • 2022-01-23
  • 2022-12-23
  • 2021-08-12
  • 2021-09-18
  • 2022-01-03
  • 2021-09-27
相关资源
相似解决方案