django圖書管理系統例項
阿新 • • 發佈:2018-12-19
首頁,其他頁面全部繼承首頁的上半部分
點擊發布圖書頁面
首頁點選書名,跳轉到圖書資訊介面,該介面可刪除圖書
專案結構
#views.py from django.shortcuts import render,redirect,reverse from django.db import connection def get_cursor(): return connection.cursor() def index(request): #首頁 cursor=get_cursor() cursor.execute("select * 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 values(null,'%s','%s')"%(name,author)) return redirect(reverse('index'))#釋出圖書完成後跳轉到首頁 def book_detail(request,book_id): cursor=get_cursor() cursor.execute("select * 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'))#刪除圖書後跳轉到首頁 else: raise RuntimeError("刪除圖書的method錯誤!")
urls.pyfrom front import views urlpatterns = [ path('', views.index,name='index'), path('add_book/',views.add_book,name='add_book'), path('book_detail/<int:book_id>',views.book_detail,name='book_detail'), path('delete_book',views.delete_book,name='delete_book') ]
專案靜態檔案index.css
*{margin:0; padding:0; } .nav { background: #3a3a3a; height: 65px; overflow: hidden } .nav li{ float:left; list-style: none; margin: 0 20px; line-height: 65px; } .nav li a{ color: #fff; text-decoration: none }
模板html,其他模板均繼承這個模板
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> <link rel="stylesheet" href="{% static 'base.css' %}"> </head> <body> <nav> <ul class="nav"> <li><a href="/">首頁</a></li> <li><a href="{% url 'add_book' %}">釋出圖書</a></li> </ul> </nav> {% block content %} {% endblock %} </body> </html>
首頁模板
{% extends 'base.html' %} {% block content %} <table> <thead> <tr> <th>序號</th> <th>書名</th> <th>作者</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'book_detail' book_id=book.0 %}">{{ book.1 }}</a></td> <td>{{ book.2 }}</td> </tr> {% endfor %} </tbody> </table> {% endblock %}
釋出圖書模板
{% extends 'base.html' %} {% block content %} <form action="" method="post"> <table> <tbody> <tr> <td>書名:</td> <td><input type="text" name='name'></td> </tr> <tr> <td>作者:</td> <td><input type="text" name='author'></td> </tr> <tr> <td></td> <td><input type="submit" value='提交'></td> </tr> </tbody> </table> </form> {% endblock %}
圖書詳情模板,該模板可刪除圖書
{% extends 'base.html' %} {% block content %} <p>書名:{{ book.1 }}</p> <p>作者:{{ book.2 }}</p> <form action="{% url 'delete_book' %}" method="post"> <input type="hidden" name="book_id" value="{{ book.0 }}"> <input type="submit" value="刪除圖書"> </form> {% endblock %}