django开发(7)使用模板

来源:互联网 发布:ubuntu 14.04安装qq 编辑:程序博客网 时间:2024/05/17 11:06

1.在与booktest同级目录下,建一个template文件夹,在template文件夹下再建一个booktest目录(因为将来还会有其它应用的模板),

在template/booktest目录下建一个index.html文件作为mvt的template调用


2.编辑views.py文件,在方法中调用模板

from django.http import HttpResponse

from django.template import RequestContext,loader

from models import BookInfo


def index(request):

      booklist = BookInfo.objects.all()

      template = loader.get_template('booktest/index.html')

      context = RequestContext(request,{'booklist':booklist})

      return HttpResponse(template.render(context))

def detail(request,id):

      book = BookInfo.objects.get(pk=id)

      template = loader.get_template('booktest/detail.html')

      context = RequestContext(request,{'book':book})

      return HttpResponse(template.render(context))


模板

模板是html页面,可以根据视图中传递的数据填充值

创建模板的目录如下图:

templates

      booktest

             index.html


修改settings.py文件,设置TEMPLATES的DIRS值

'DIRS':[os.path.join(BASE_DIR,'templates')],


在模板中访问视图传递的数据

{{输出值,可以是变量,也可以是对象.属性}}

{%执行代码段%}






原创粉丝点击