day07-综合案例

2020-01-29  本文已影响0人  wenyilab

1、视图函数

def show_books(request):
    '''显示图书信息'''
    # 1、查找图书表信息,导入图书模型类
    books = BookInfo.objects.all()
    return render(request,'booktest/show_books.html',
                  {'books':books})
def detail(request,bid):
    '''查出图书关联的英雄信息'''
    # 根据bid查出图书英雄信息
    book = BookInfo.objects.get(id=bid)
    print(book)
    # 查询和book相关的英雄信息
    heros = book.heroinfo_set.all()
    # 使用模版
    return render(request,'booktest/detail.html',
              {'book':book,'heros':heros})

2、模版文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>显示图书信息</title>
</head>
<body>
图书信息如下:
<ul>
    {% for book in books %}
        <li><a href="/booktest/books/{{ book.id }}">{{ book.btitle }}<a/></li>
    {% endfor %}
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>显示图书关联的英雄信息</title>
</head>
<body>
<h1>{{ book.btitle }}</h1>
英雄信息如下:
<ul>
    {% for hero in heros %}
        <li>{{ hero.hname }}--{{ hero.hcomment }}</li>
    {% empty %}
        <li>没有英雄信息</li>
    {% endfor %}
</ul>
</body>
</html>

3、urls文件

urlpatterns = [
    # 通过url函数设置url路由配置项
    path('index/',views.index),
    path('books/',views.show_books),
    # path('books/(\d+)/',views.detail),
    url(r'^books/(\d+)$',views.detail),
    path('books/test/',views.test)
]

4、效果图


show_books
detail_1
detail_2
上一篇 下一篇

猜你喜欢

热点阅读