<html lang="en">
<head>
<meta charset="UTF-8">
<title>书籍信息表</title>
</head>
<body>
<table border="1">
<tr>
<th>id</th>
<th>title</th>
<th>price</th>
<th> retail_price</th>
<th>public</th>
<th>option</th>
</tr>
{% for book in all_book %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.retail_price }}</td>
<td>{{ book.pub.pubname }}</td>
<td>
<a href="/index/update_book/{{ book.id }}">更新</a>
<a href="/index/delete_book/{{ book.id }}">删除</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
上述代码中我们我们构建了一个有关书籍信息表的表格,下面就需要在 index.views.py 文件中编写视图层代码逻辑了,代码如下所示:
"""
time: 22/6
item: Book CURD
"""
def book_table(request):
try:
all_book=Book.objects.all().order_by('-price')
if not all_book:
return HttpResponse('书籍信息表为空,请录入!')
except Exception as e:
print(e)
return render(request, 'index/book_table.html', locals())
并配置路由映射关系,最后访问 http://127.0.0.1:8000/index/all_book/ 可得如下界面显示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加书籍信息</title>
</head>
<body>
<form action="/index/add_book/" method="post">
{% csrf_token %}
<p>
title : <input type="text" name="title">
</p>
<p>
price : <input type="text" name="price">
</p>
<p>
retail_price : <input type="text" name="retail_price">
</p>
<p>
public : <input type="text" name="pub">
</p>
<p>
<!--按钮的值提交--> <input type="submit" value="提交">
</p>
</form>
</body>
</html>
def add_book(request):
if request.method == 'GET':
return render(request, 'index/add_book.html')
elif request.method == 'POST':
#添加书籍
title = request.POST.get('title')
if not title:
return HttpResponse('请给出一个正确的title')
pub = request.POST.get('pub')
price = float(request.POST.get('price','999.99'))
if not price:
return HttpResponse('请输入价格')
try:
retail_price = float(request.POST.get('retail_price'))
if not retail_price:
return HttpResponse('请输入市场价')
except Exception as e:
print(e)
#判断title是不是已经存在了
old_book = Book.objects.filter(title=title)
if old_book:
return HttpResponse('你输入的书籍系统已经存在 !')
try:
pub1=PubName.objects.get(pubname=str(pub))
Book.objects.create(title=title,price=price,retail_price=retail_price,pub=pub1)
except Exception as e:
print('Add ErrorReason is %s'%(e))
return HttpResponseRedirect('/index/all_book')
return HttpResponse('请使用正确Http请求方法 !')
最后将路由映射关系配置完成,通过上面的代码我们就完成书籍信息的添加的功能,访问 127.0.0.1/index/add_book,可得如下界面:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有