Django入门学习(5)——模版

本文通过实例演示了如何使用 Django 的 ORM 功能进行数据库操作,包括获取书籍列表并展示所有英雄角色等内容。具体实现了从数据库中读取数据,并在前端页面上显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

step1 : booktest/views.py

from django.shortcuts import render
from django.http import *
# from django.template import RequestContext,loader
from .models import *


# Create your views here.
def index(request):
    # temp = loader.get_template('booktest/index.html')
    # return HttpResponse(temp.render())
    bookList = BookInfo.objects.all()
    context = {'list':bookList}
    return render(request,'booktest/index1.html',context)

def show(request,id):
    book = BookInfo.objects.get(pk=id)
    heroList = book.heroinfo_set.all()
    context = {'list':heroList}
    return render(request,'booktest/show.html',context)

step2: templates/booktest/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>
<ul>
{%for book in list%}
<li><a href="{{book.id}}">{{book.btitle}}</a></li>
{%endfor%}
</ul>
</body>
</html>

step3:templates/booktest/show.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Title</title>
</head>
<body>
<ul>
{%for hero in list%}
<li>{{hero.hname}}</li>
{%endfor%}
</ul>
</body>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值