完成示例項目
現在還需要的代碼包括三個方面,三個方面順序不分先後。
- 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 = [
#配置首頁url
url(r'^$', views.index),
#配置詳細頁url,\d+表示多個數字,小括号用于取值,建議複習下正規表達式
url(r'^(\d+)/$',views.detail),
]
定義模闆
<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>
<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>