项目的路由配置代码
# project->urls.py
from django.urls import path,include,re_path
from index import views
urlpatterns = [
path('current_time',views.current_datetime),
]
阶段一 单纯响应输出字符串
# project->app->views.py
from django.http import HttpResponse
from datetime import datetime
# 使用HttpResponnse返回字符串
def current_datetime(request):
now_time = datetime.now()
html = "<html><body>Current time is: %s</body></html>" % now_time
return HttpResponse(html)
阶段二 利用Django模板系统打印响应输出字符串
# project->app->views.py
from django.http import HttpResponse
from datetime import datetime
from django.template import Context,Template
# 初步利用Django的模板系统
def current_datetime(request):
current = datetime.now()
t = Template("<html><body>Current Datetime is : {{current_time}}!</body></html>")
html = t.render(Context({'current_time':current}))
return HttpResponse(html)
这里存在一个问题就是,模板代码与Python代码仍旧是夹杂存在的,这一点是极度不友好,为了将views与templates分离,可以继续如下优化
阶段三 简单利用Template模板系统
<!--在项目的运行目录下新建demo.html文件-->
<!DOCTYPE html>
<html>
<head>
<title>demo当前时间</title>
</head>
<body>
<h1>demo.html: It is now {{ current_date}}.</h1>
</body>
</html>
# project->app->views.py
from django.template import Template, Context
from django.http import HttpResponse
import datetime
# 这里初步将template与views.py代码做到分离了
def current_date(request):
now_time = datetime.now()
# print(os.getcwd())
cur_path = os.getcwd()
fp = open('%s/demo.html' % cur_path,encoding='utf-8')
t = Template(fp.read())
fp.close()
html = t.render(Context({'current_date': now_time}))
return HttpResponse(html)
但是这样会引发其他的问题是:
- 因为没有考虑缺少template文件的情况,比如demo.html文件不存在,open函数就会抛出IOError
异常 - 模板位置是硬编码的。如果每个视图函数都这么做,要重复编写模板的位置。更别提要输入很多内容
了! - 有大量乏味的样板代码。何每次加载模板时要浪费时间编写open()、fp.read() 和 fp.close() 调用
阶段四 深入熟悉Templates模板系统机制
- 引入Templates文件夹
- 了解project-》setting.py-》TEMPLATES 作用
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... 一些选项 ...
},
},
]
1、DIRS 定义一个目录列表,模板引擎按顺序在里面查找模板源文件。
- 如果不是构建没有应用的极简程序,最好留空DIRS。设置文件默认把APP_DIRS 设为True,因此最好
在 Django 应用中放一个“templates”子目录。
- 如果想在项目根目录中放一些主模板(例如在mysite/templates 目录中),需要像这样设定DIRS:
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)]
- 在 Windows 中要加上盘符,而且要使用 Unix 风格的正斜线,而不是反斜线,如下所示:
'DIRS': ['C:/www/django/templates'],
2、APP_DIRS 设定是否在安装的应用中查找模板。(按约定,APPS_DIRS 设为True 时,DjangoTemplates 会在
INSTALLED_APPS 中的各个应用里查找名为“templates”的子目录。这样,即使DIRS 为空,模板引擎还能
查找应用模板。)
3、OPTIONS 是一些针对后端的设置。(暂时没弄明白)
# project->app->views.py
from django.template import Template, Context
from django.http import HttpResponse
import datetime
from django.template.loader import get_template
def now_time(request):
now_date = datetime.now()
text = get_template('now_time.html')
# msg = text.render(Context({'current_date':now_date})) # 这里这样写会报错的,改为下面字典形式即可!
msg = text.render({'current_date':now_date})
return HttpResponse(msg)