學習筆記,僅供參考,有錯必究
製作圖書管理系統
我們基於上一個博客Django(part38)–製作登錄界面的mywebsite_bookstore項目,製作一個圖書管理系統。
第一步
向數據庫中添加一些圖書信息
首先我們先創建後臺管理賬號:
F:\MyStudio\PythonStudio\goatbishop.project01\Django\mywebsite_bookstore>python manage.py createsuperuser
Username (leave blank to use 'goatbishop'):
Email address: [email protected]
Password:
Password (again):
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: N
Password:
Password (again):
Superuser created successfully.
我們打開bookstore應用下的admin.py,並進行註冊:
from django.contrib import admin
from . import models
# Register your models here.
class Book_Manager(admin.ModelAdmin):
list_display = ['title', 'pub_house','price', 'market_price']
list_filter = ['pub_house']
search_fields = ['title', 'pub_house']
list_editable = ['market_price']
admin.site.register(models.Book, Book_Manager)
開啓服務,進入admin數據庫後臺管理系統,隨便添加幾本書:
第二步
設置登錄用戶可以瀏覽、刪除、修改和添加圖書信息,但是未登錄的用戶,只能瀏覽圖書信息,無權更改。
首先,我們在主模板文件夾下,修改主頁homepage.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
{# 判斷是否有userinfo來確定是否已經登陸 #}
{% if request.session.userinfo %}
歡迎:{{request.session.userinfo.username }}
<br>
<a href="/userinfo/logout/">退出登錄</a>
<br><br>
<div>
<a href="/bookstore/add/">添加新書</a>
<a href="/bookstore/list_all/">查看全部圖書</a>
</div>
{% else %}
<ul>
<li><a href="/userinfo/login/">登陸</a></li>
<li><a href="/userinfo/reg/">註冊</a></li>
</ul>
遊客, 您可以<a href="/bookstore/list_all/">查看全部圖書</a>
<br><br>
若您想對書籍信息進行修改,請先登錄!
{% endif %}
</body>
</html>
如果我們在登錄狀態下,主頁是這樣的:
在未登錄狀態下,主頁是這樣的:
我們先在bookstore應用下的urls.py模塊中添加路由:
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$', views.homepage),
re_path(r'^add/$', views.new_book),
re_path(r'^list_all/$', views.list_books),
re_path(r'^mod/(\w+)/$', views.mod_book_info),
re_path(r'^del/(\w+)/$', views.del_book),
]
再bookstore應用下的views.py模塊中添加視圖函數:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from . import models
from django.http import Http404
def homepage(request):
return render(request, 'index.html')
def new_book(request):
# 爲添加新收功能提供權限驗證
if 'userinfo' not in request.session:
raise Http404
if request.method == 'GET':
return render(request, 'new_book.html')
elif request.method == 'POST':
title = request.POST.get('title', '')
pub_house = request.POST.get('pub_house', '')
price = request.POST.get('price', '')
market_price = request.POST.get('market_price', '')
# 用Book.object管理器的create方法來創建新書
abook = models.Book.objects.create(title=title,
price=price,
market_price=market_price,
pub_house=pub_house)
print('添加新書,成功添加新書:', abook.title)
return HttpResponse('<a href="/bookstore/">添加新書成功,點我跳轉到書庫</a>')
def list_books(request):
books = models.Book.objects.all()
return render(request, 'book_list.html', locals())
def mod_book_info(request, book_name):
# 先根據book_id 找到對應的一本書
try:
abook = models.Book.objects.get(title = book_name)
except:
return HttpResponse("沒有找到" + book_name + "的圖書信息")
if request.method == 'GET':
return render(request, "mod_price.html", locals())
elif request.method == 'POST':
try:
m_price = request.POST.get('market_price', '0.0')
abook.market_price = m_price
abook.save() # 提交修改
html = "修改成功 <div><a href='/bookstore/list_all/'>回到書籍瀏覽界面</a></div>"
return HttpResponse(html)
except:
return HttpResponse("修改失敗")
from django.http import HttpResponseRedirect # 改入 HttpResponseRedirect模塊用於 重定向url
def del_book(request, book_name):
try:
abook = models.Book.objects.get(title = book_name)
abook.delete()
return HttpResponseRedirect('/bookstore/list_all/')
except:
return HttpResponse("沒有找到" + book_name + "的圖書信息,刪除失敗")
在主模板文件夾下創建各種模板。
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>書庫</title>
</head>
<body>
<ul>
{% if request.session.userinfo %}
<li><a href="/bookstore/add/">添加新圖書</a></li>
<li><a href="/bookstore/list_all/">顯示所有圖書</a></li>
{% else %}
<li><a href="/bookstore/list_all/">顯示所有圖書</a></li>
{% endif %}
</ul>
</body>
</html>
mod_price.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改價格</title>
</head>
<body>
<form action="/bookstore/mod/{{ abook.title }}/" method="post">
<div>書名: {{ abook.title }}</div>
<div>版社名: {{ abook.pub_house }}</div>
<div>定價: {{ abook.price }}</div>
<div>
零售價:<input type="text" name="market_price" value="{{ abook.market_price }}"placeholder="零售價" required>
</div>
<div>
<input type="submit" value="修改價格">
</div>
</form>
</body>
</html>
new_book.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加新書</title>
</head>
<body>
<form action="/bookstore/add/" method="post">
<div>
<input type="text" name="title" placeholder="新書名" required value="書名">
</div>
<div>
<input type="text" name="pub_house" placeholder="新版社名" required>
</div>
<div>
<input type="text" name="price" placeholder="定價" required>
</div>
<div>
<input type="text" name="market_price" placeholder="零售價" required>
</div>
<div>
<input type="submit" value="添加新書">
</div>
</form>
</body>
</html>
book_list.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圖書列表</title>
</head>
<body>
<a href="/bookstore/">進入書庫</a>
<a href="/">返回首頁</a>
<table>
<tr>
<th>書名</th>
<th>出版社</th>
<th>定價</th>
<th>零售價</th>
<th>修改</th>
<th>刪除</th>
</tr>
{% for abook in books %}
<tr>
<td>{{ abook.title }}</td>
<td>{{ abook.pub_house }}</td>
<td>{{ abook.price }}</td>
<td>{{ abook.market_price }}</td>
{% if request.session.userinfo %}
<td><a href="/bookstore/mod/{{ abook.title }}">修改</a></td>
<td><a href="/bookstore/del/{{ abook.title }}">刪除</a></td>
{% else %}
<td colspan="2">您無權更改</td>
{% endif %}
</tr>
{% endfor %}
</table>
</body>
</html>
第三步
圖書管理系統使用演示
我們開啓服務,並向首頁發起請求(非登錄狀態):
點擊查看全部圖書
,進入所有圖書列表:
點擊進入書庫
:
點擊顯示所有圖書
,返回所有圖書列表。
在登錄狀態下,向首頁發起請求:
點擊添加新書
,並按照字段類型添加書籍:
添加成功後,自動跳轉到如下頁面,我們點擊這個超鏈接,進入書庫:
點擊顯示所有圖書
:
我們又一次進入到了圖書列表,但這次由於我們處於登錄狀態,所以可以對書籍進行修改和刪除: