1.网站组成
首页:通过首页可以看到已经发布的图书
发布图书页面:负责发布图
图书详情:展示图书的ID作者
程序结构
url为路由配置首页,图书发布,图书详情,删除图书四个路由
setting负责配置数据库,导入模版,关闭csrf,安装app
APP文件中视图函数有四个,css样式文件有一个,与模型中的HTML文件进行交互
HTML采用继承的方式使得代码更加简洁
存在问题
1.版本过低:由于MySQL版本过低导致无法调用数据库
解决办法:MySQL卸载重装
2.模版未导入:由于在旧的版本中模版已存在所以旧版不用导入模版,而新版需要自己创建模版
解决办法:在setting中导入模版
拼写错误:
3.PEP8:根据提示,进行更改,代码更美观
4.数据库主键没有设定自增,导致无法插入多条数据
代码组成
视图
from django.shortcuts import render, redirect, reverse
from django.db import connection
# Create your views here.
def get_cursor():
return connection.cursor()
def index(request):
cursor = get_cursor()
cursor.execute("select id,name,author from book")
books = cursor.fetchall()
return render(request, 'index.html', context={
"books": books})
def add_book(request):
if request.method == 'GET':
return render(request, 'add_book.html')
else:
name = request.POST.get("name")
author = request.POST.get("author")
cursor = get_cursor()
cursor.execute("insert into book(name, author) values ('%s', '%s')"%(name, author))
return redirect(reverse('index'))
def book_detail(request,book_id):
cursor =get_cursor()
cursor.execute("select id, name, author from book where id=%s" %book_id)
book = cursor.fetchone()
return render(request,'book_detail.html', context={
"book":book})
def delete_book(request):
if request.method == 'POST':
book_id = request.POST.get('book_id')
cursor=get_cursor()
cursor.execute("delete from book where id=%s" %book_id)
return redirect(reverse('index')