Django中template导入文件
template文件的导入template文件就是普通的文件,需要用于template.render()函数渲染,可以有以下几种方法来加载文件1.用python自带的open()函数,如:from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):now = datetime.datetime.now()# Simple way of using templates from the filesystem.# This is BAD because it doesn't account for missing files!fp = open('/home/djangouser/templates/mytemplate.html')t = Template(fp.read())fp.close()html = t.render(Context({'current_date': now}))return HttpResponse(html)这种方法有点费事儿,需要打开和关闭文件2.用template的加载api在项目的settings.py文件中,找到TEMPLATE_DIRS,然后添加近你的template的目录如:TEMPLATE_DIRS = ('/home/django/mysite/templates',)注意,后面有一个逗号,这个是python的元组中特别规定的这中方法有点古板3.将template文件创建在你的项目下,这样查找就比较 方便了,可以这样:import os.pathTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),)这里的做法是:获取当前文件(setting.py)的路径,然后加上templates,并把如果有反斜杠的路径转换为斜杠,这样就定位到了templates目录4.直接不修改文件,django中的django.template.loaders.app_directories.Loader将自动查找项目下的所有templates文件,这样就不用指定路径了在view中导入相应的templatefrom 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') #返回一个template对象html = t.render(Context({'current_date': now}))#调用render方法进行渲染return HttpResponse(html)这里的对于模板的后缀名没有限制,其实,模板只是起到把字符存储的作用,最终有template的加载函数把数据读出来,然后在渲染在上面的使用中,还是比较麻烦,需要导入文件,然后构造一个Context,然后调用render()函数进行渲染可以使用更简单的方法来做这样的事情在Django中提供了一个模块django.shortcuts,里面有很多快捷的方法可以使用,如render()方法,如:from django.shortcuts import renderimport datetimedef current_datetime(request): now = datetime.datetime.now() return render(request, 'current_datetime.html', {'current_date': now})有什么不同呢:1、这里及导入template文件,构造Context,生成一个HttpResponse对象于一句代码,非常完美这个函数返回一个经过渲染的HttpResponse对象2、不用再引入Context,Template,HttpResponse,相反只需要引入django.shortcuts.render闲说一下,我现在非常喜欢python,代码简洁,还很透明,你想知道什么都可以查到,希望大家一起分享python的经验