完成示例項目
現在還需要的代碼包括三個方面,三個方面順序不分先后。
- 1.定義視圖
- 2.定義URLconf
- 3.定義模板
定義視圖
編寫booktest/views.py文件如下:
from django.shortcuts import render
from booktest.models import BookInfo#首頁,展示所有圖書
def index(reqeust):#查詢所有圖書booklist = BookInfo.objects.all()#將圖書列表傳遞到模板中,然后渲染模板return render(reqeust, 'booktest/index.html', {'booklist': booklist})#詳細頁,接收圖書的編號,根據編號查詢,再通過關系找到本圖書的所有英雄并展示
def detail(reqeust, bid):#根據圖書編號對應圖書book = BookInfo.objects.get(id=int(bid))#查找book圖書中的所有英雄信息heros = book.heroinfo_set.all()#將圖書信息傳遞到模板中,然后渲染模板return render(reqeust, 'booktest/detail.html', {'book':book,'heros':heros})
定義URLconf
編寫booktest/urls.py文件如下:
from django.conf.urls import url
#引入視圖模塊
from booktest import views
urlpatterns = [#配置首頁urlurl(r'^$', views.index),#配置詳細頁url,\d+表示多個數字,小括號用于取值,建議復習下正則表達式url(r'^(\d+)/$',views.detail),
]
定義模板
編寫templates/booktest/index.html文件如下:
<html>
<head><title>首頁</title>
</head>
<body>
<h1>圖書列表</h1>
<ul>{#遍歷圖書列表#}{%for book in booklist%}<li>{#輸出圖書名稱,并設置超鏈接,鏈接地址是一個數字#}<a href="/{{book.id}}/">{{book.btitle}}</a></li>{%endfor%}
</ul>
</body>
</html>
編寫templates/booktest/detail.html文件如下:
<html>
<head><title>詳細頁</title>
</head>
<body>
{#輸出圖書標題#}
<h1>{{book.btitle}}</h1>
<ul>{#通過關系找到本圖書的所有英雄,并遍歷#}{%for hero in heros%}{#輸出英雄的姓名及描述#}<li>{{hero.hname}}---{{hero.hcomment}}</li>{%endfor%}
</ul>
</body>
</html>