展示
def books(request):
book_list = Book.objects.all()
return render(request, "books.html", {"book_list": book_list})
添加
def addbook(request):
if request.method == "POST":
# 获取用户提交的数据
title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("pub_date")
publish = request.POST.get("publish")
book = Book.objects.create(title=title, price=price, pub_date=pub_date, publish=publish)
return redirect(reverse("books"))
else:
return render(request, "addbook.html")
鼠标放在添加书籍按钮,浏览器左下角有一个地址
删除
def delbook(request, nid):
Book.objects.get(pk=nid).delete()
return redirect(reverse("books"))
修改
def update_book(request, nid):
if request.method == 'GET':
book = Book.objects.get(pk=nid)
return render(request, 'update_book.html', locals())
else:
title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("pub_date")
publish = request.POST.get("publish")
return redirect(reverse("books"))
鼠标点击最后第五本书籍,来到对应的编辑页面,并且表单中有它的信息,将其修改
URL配置
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/$', views.books, name="books"),
url(r'^books/add/$', views.addbook),
url(r'^books/delete/(?P<nid>d+)$', views.delbook),
url(r'^books/update/(d+)$', views.update_book),
]
补充
在创建书籍和修改书籍时,代码中总要一个一个的获取书籍信息,然后再一个一个的进行提交,很是麻烦。可以先将获取的数据转成字典格式,然后再进行添加或修改