模板
- 模板是html頁(yè)面感局,可以根據(jù)視圖中傳遞的數(shù)據(jù)填充值
- 創(chuàng)建模板的目錄如下圖:
day44_Django入門(mén)-01.png
- 修改settings.py文件,設(shè)置TEMPLATES的DIRS值
'DIRS': [os.path.join(BASE_DIR, 'templates')],
- 在模板中訪問(wèn)視圖傳遞的數(shù)據(jù)
{{輸出值蹋嵌,可以是變量,也可以是對(duì)象.屬性}}
{%執(zhí)行代碼段%}
定義index.html模板
<!DOCTYPE html>
<html>
<head>
<title>首頁(yè)</title>
</head>
<body>
<h1>圖書(shū)列表</h1>
<ul>
{%for book in booklist%}
<li>
<a href="{{book.id}}">
{{book.btitle}}
</a>
</li>
{%endfor%}
</ul>
</body>
</html>
定義detail.html模板
- 在模板中訪問(wèn)對(duì)象成員時(shí)葫隙,都以屬性的方式訪問(wèn)栽烂,即方法也不能加括號(hào)
<!DOCTYPE html>
<html>
<head>
<title>詳細(xì)頁(yè)</title>
</head>
<body>
<h1>{{book.btitle}}</h1>
<ul>
{%for hero in book.heroinfo_set.all%}
<li>{{hero.hname}}---{{hero.hcontent}}</li>
{%endfor%}
</ul>
</body>
</html>
使用模板
- 編輯views.py文件,在方法中調(diào)用模板
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(reqeust, id):
book = BookInfo.objects.get(pk=id)
template = loader.get_template('booktest/detail.html')
context = RequestContext(reqeust, {'book': book})
return HttpResponse(template.render(context))
去除模板的硬編碼
- 在index.html模板中恋脚,超鏈接是硬編碼的愕鼓,此時(shí)的請(qǐng)求地址為“127.0.0.1/1/”
<a href="{{book.id}}">
- 看如下情況:將urlconf中詳細(xì)頁(yè)改為如下,鏈接就找不到了
url(r'^book/([0-9]+)/$', views.detail),
- 此時(shí)的請(qǐng)求地址應(yīng)該為“127.0.0.1/book/1/”
- 問(wèn)題總結(jié):如果在模板中地址硬編碼慧起,將來(lái)urlconf修改后菇晃,地址將失效
- 解決:使用命名的url設(shè)置超鏈接
- 修改test1/urls.py文件,在include中設(shè)置namespace
url(r'^admin/', include(admin.site.urls, namespace='booktest')),
- 修改booktest/urls.py文件蚓挤,設(shè)置name
url(r'^book/([0-9]+)/$', views.detail, name="detail"),
<a href="{%url 'booktest:detail' book.id%}">
Render簡(jiǎn)寫(xiě)
- Django提供了函數(shù)Render()簡(jiǎn)化視圖調(diào)用模板磺送、構(gòu)造上下文
from django.shortcuts import render
from models import BookInfo
def index(reqeust):
booklist = BookInfo.objects.all()
return render(reqeust, 'booktest/index.html', {'booklist': booklist})
def detail(reqeust, id):
book = BookInfo.objects.get(pk=id)
return render(reqeust, 'booktest/detail.html', {'book': book})