当前位置:K88软件开发文章中心网站服务器框架django → 文章内容

Django 模版进阶

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-25 14:19:14

部变量 file ,该变量被自动设置为代码所在的 Python 模块文件名。 os.path.dirname(__file__) 将会获取自身所在的文件,即settings.py 所在的目录,然后由os.path.join 这个方法将这目录与 templates 进行连接。如果在windows下,它会智能地选择正确的后向斜杠”“进行连接,而不是前向斜杠”/”。在这里我们面对的是动态语言python代码,我需要提醒你的是,不要在你的设置文件里写入错误的代码,这很重要。 如果你在这里引入了语法错误,或运行错误,你的Django-powered站点将很可能就要被崩溃掉。完成 TEMPLATE_DIRS 设置后,下一步就是修改视图代码,让它使用 Django 模板加载功能而不是对模板路径硬编码。 返回 current_datetime 视图,进行如下修改:from django.template.loader import get_templatefrom django.template import Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date': now})) return HttpResponse(html)此范例中,我们使用了函数 django.template.loader.get_template() ,而不是手动从文件系统加载模板。 该get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的Template 对象。在这个例子里,我们选择的模板文件是current_datetime.html,但这个与.html后缀没有直接的联系。 你可以选择任意后缀的任意文件,只要是符合逻辑的都行。甚至选择没有后缀的文件也不会有问题。要确定某个模板文件在你的系统里的位置, get_template()方法会自动为你连接已经设置的 TEMPLATE_DIRS目录和你传入该法的模板名称参数。比如,你的 TEMPLATE_DIRS目录设置为 '/home/django/mysite/templates',上面的 get_template()调用就会为你找到 /home/django/mysite/templates/current_datetime.html 这样一个位置。如果 get_template() 找不到给定名称的模板,将会引发一个 TemplateDoesNotExist 异常。 要了解究竟会发生什么,让我们按照第三章内容,在 Django 项目目录中运行 python manage.py runserver 命令,再次启动Django开发服务器。 接着,告诉你的浏览器,使其定位到指定页面以激活current_datetime视图(如http://127.0.0.1:8000/time/ )。假设你的 DEBUG项设置为 True,而你有没有建立current_datetime.html 这个模板文件,你会看到Django的错误提示网页,告诉你发生了 TemplateDoesNotExist 错误。图 4-1: 模板文件无法找到时,将会发送提示错误的网页给用户。该页面与我们在第三章解释过的错误页面相似,只不过多了一块调试信息区: 模板加载器事后检查区。 该区域显示 Django 要加载哪个模板、每次尝试出错的原因(如:文件不存在等)。 当你尝试调试模板加载错误时,这些信息会非常有帮助。接下来,在模板目录中创建包括以下模板代码 current_datetime.html 文件:<html><body>It is now {{ current_date }}.</body></html>在网页浏览器中刷新该页,你将会看到完整解析后的页面。render_to_response()我们已经告诉你如何载入一个模板文件,然后用 Context渲染它,最后返回这个处理好的HttpResponse对象给用户。 我们已经优化了方案,使用 get_template() 方法代替繁杂的用代码来处理模板及其路径的工作。 但这仍然需要一定量的时间来敲出这些简化的代码。 这是一个普遍存在的重复苦力劳动。Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。该捷径就是位于 django.shortcuts 模块中名为 render_to_response() 的函数。大多数情况下,你会使用``\ [](http://docs.30c.org/djangobook2/chapter04/index.html#id21)[``](http://docs.30c.org/djangobook2/chapter04/index.html#id23)对象,除非你的老板以代码行数来衡量你的工作。System Message: WARNING/2 (, line 1736); backlinkInline literal start-string without end-string.System Message: WARNING/2 (, line 1736); backlinkInline literal start-string without end-string.System Message: WARNING/2 (, line 1736); backlinkInline literal start-string without end-string.下面就是使用 render_to_response() 重新编写过的 current_datetime 范例。from django.shortcuts import render_to_responseimport datetimedef current_datetime(request): now = datetime.datetime.now() return render_to_response('current_datetime.html', {'current_date': now})大变样了! 让我们逐句看看代码发生的变化:

上一页  [1] [2] [3] [4] [5] [6] [7] 


Django 模版进阶