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")
鼠標放在添加書籍按鈕,瀏覽器左下角有一個地址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"))
鼠標點擊最後第五本書籍,來到對應的編輯頁面,而且表單中有它的信息,將其修改python
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), ]
在建立書籍和修改書籍時,代碼中總要一個一個的獲取書籍信息,而後再一個一個的進行提交,非常麻煩。能夠先將獲取的數據轉成字典格式,而後再進行添加或修改瀏覽器