Django模板Template(实验楼学习笔记)

(1)创建模板

首先在 mysite/lib 目录里创建一个 templates 目录。

Django 将会在这个目录里查找模板文件。

新建模板文件 lib/templates/lib/detail.html ,并向其中写入如下代码:

# lib/templates/lib/detail.html
<h1>Book List</h1>
<table>
    <tr>
        <td>书名</td>
        <td>作者</td>
        <td>出版社</td>
        <td>出版时间</td>
    </tr>
{% for book in book_list.all %}
    <tr>
        <td>{{ book.name }}</td>
        <td>{{ book.author }}</td>
        <td>{{ book.pub_house }}</td>
        <td>{{ book.pub_date }}</td>
    </tr>
{% endfor %}
</table>

(2)创建视图来返回图书列表:

# mysite/lib/views.py
from django.shortcuts import render
from .models import Book

def detail(request):
    book_list = Book.objects.order_by('-pub_date')[:5]
    context = {'book_list': book_list}
    return render(request, 'lib/detail.html', context)

(3)绑定连接

将新视图添加进lib.urls模块里:

# lib/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('detail/', views.detail, name='detail'),
]

(4)运行命令:python3 manage.py runserver 

扫描二维码关注公众号,回复: 4541395 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_39112101/article/details/84886880