程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python基於mysql+Django框架圖書管理系統源代碼(含mysql文件)

編輯:Python

項目前台和後台界面模板都是自己編寫,前台采用Bootstrap框架UI,後台EasyUI框架UI,沒有采用Django自動生成的那個後台管理,因為那個後台實在是太丑了,丑得慘不忍睹!整個項目主要負責圖書信息的添加,修改,多個條件組合查詢,刪除。雖然系統功能不是很復雜,不過這是一個很好的學習案例,包括了常用字段的設計,比如字符串,浮點型,整型,日期型,圖片型,富文本字符串型,文件型和下拉框外鍵關聯型,囊括了所有商業項目設計需要的字段類型,通殺所有商業系統設計原理!當然也是學習的不二選擇,好東西值得分享,強烈推薦.後台登錄用戶名密碼均為a。
系統實體對象:
圖書類型:圖書類別,類別名稱,可借閱天數
圖書:圖書條形碼,圖書名稱,圖書所在類別,圖書價格,庫存,出版日期,出版社,圖書圖片,圖書簡介,圖書文件。
程序運行截圖


核心代碼

""" Django settings for PythonProject project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'fav!(r-3=i+bya!meg=vw*zcn-$4g3vhav!!)mw=f!b)7+7it2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.Index', #首頁模塊
'apps.BookType', #圖書分類模塊
'apps.Book', #圖書信息模塊
'tinymce', #富文本編輯器
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'PythonProject.urls'
TEMPLATES = [
{

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {

'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'PythonProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_book',
'USER': 'root',
'PASSWORD': 'sxing86',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{

'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{

'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace("\\", "/")
MEDIA_URL = '/media/'
# 配置session存儲
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
#富文本編輯器配置
TINYMCE_DEFAULT_CONFIG = {

'theme': 'simple',
'width': '100%',
'height': '300px',
}

BookType/views.py

from django.views.generic import View
from django.shortcuts import render
from apps.BookType.models import BookType
from django.core.paginator import Paginator
from django.http import JsonResponse
class FrontAddView(View):
def get(self,request):
pass
def post(self,request):
pass
class ListAllView(View):
def get(self,request):
bookTypes = BookType.objects.all()
bookTypeList = []
for bookType in bookTypes:
bookTypeObj = {

'bookTypeId': bookType.bookTypeId,
'bookTypeName': bookType.bookTypeName,
}
bookTypeList.append(bookTypeObj)
return JsonResponse(bookTypeList,safe=False)
class FrontListView(View):
def get(self,request):
pageSize = 5
currentPage = request.GET.get("currentPage")
bookTypes = BookType.objects.all()
paginator = Paginator(bookTypes, pageSize)
totalPage = paginator.num_pages
recordNumber = paginator.count
# 獲取第page頁的內容
try:
currentPage = int(currentPage)
except Exception as e:
currentPage = 1
if currentPage > totalPage:
currentPage = totalPage
# 獲取第page頁的Page實例對象
bookTypes_page = paginator.page(currentPage)
startIndex = (currentPage - 1) * pageSize #計算起始序號
startPage = currentPage - 5
endPage = currentPage + 5
if startPage < 1:
startPage=1
if endPage > totalPage:
endPage = totalPage;
pageList = list(range(startPage,endPage+1))
context = {

'bookTypes_page': bookTypes_page,
'currentPage': currentPage,
'totalPage': totalPage,
'recordNumber': recordNumber,
'startIndex': startIndex,
'pageList': pageList,
}
print(pageList)
# 使用模板
return render(request, 'BookType/bookType_frontquery_result.html', context)
def post(self,request):
pass

Book/views.py

from django.views.generic import View
from apps.BaseView import BaseView
from django.shortcuts import render
from django.core.paginator import Paginator
from apps.Book.models import Book
from apps.BookType.models import BookType
from django.http import JsonResponse
from django.http import FileResponse
from apps.BaseView import ImageFormatException
from django.conf import settings
import pandas as pd
import os
class FrontAddView(BaseView): # 前台圖書添加
def primaryKeyExist(self, barcode): # 判斷主鍵是否存在
try:
Book.objects.get(barcode=barcode)
return True
except Book.DoesNotExist:
return False
def get(self,request):
bookTypes = BookType.objects.all() # 獲取所有圖書類型
context = {

'bookTypes': bookTypes,
}
# 使用模板
return render(request, 'Book/book_frontAdd.html', context)
def post(self,request):
barcode = request.POST.get('book.barcode') # 判斷圖書條形碼是否存在
if self.primaryKeyExist(barcode):
return JsonResponse({
'success': False, 'message': '圖書條形碼已經存在'})
book = Book() # 新建一個圖書對象然後獲取參數
book.barcode = barcode
book.bookName = request.POST.get('book.bookName')
book.bookTypeObj = BookType.objects.get(bookTypeId=int(request.POST.get('book.bookTypeObj.bookTypeId')))
book.price = float(request.POST.get('book.price'))
book.count = int(request.POST.get('book.count'))
book.publishDate = request.POST.get('book.publishDate')
book.publish = request.POST.get('book.publish')
try:
book.bookPhoto = self.uploadImageFile(request,'book.bookPhoto')
except ImageFormatException as ife:
return JsonResponse({
'success': False, 'message': ife.error})
book.bookDesc = request.POST.get('book.bookDesc')
book.bookFile = self.uploadCommonFile(request,'book.bookFile')
book.save() # 保存圖書信息到數據庫
return JsonResponse({
'success': True, 'message': '保存成功'})
class FrontModifyView(BaseView): # 前台修改圖書
def get(self, request, barcode):
context = {
"barcode": barcode}
return render(request, 'Book/book_frontModify.html', context)
class FrontListView(BaseView): # 前台圖書查詢列表
def get(self, request):
return self.handle(request)
def post(self, request):
return self.handle(request)
def handle(self,request):
self.getCurrentPage(request) # 獲取當前要顯示第幾頁
# 下面獲取查詢參數
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# 然後條件組合查詢過濾
book = Book.objects.all()
if barcode != '':
book = book.filter(barcode__contains=barcode)
if bookName != '':
book = book.filter(bookName__contains=bookName)
if publishDate != '':
book = book.filter(publishDate__contains=publishDate)
if bookTypeObj_bookTypeId != '0':
book = book.filter(bookTypeObj=bookTypeObj_bookTypeId)
# 對查詢結果利用Paginator進行分頁
self.paginator = Paginator(book, self.pageSize)
# 計算總的頁碼數,要顯示的頁碼列表,總記錄等
self.calculatePages()
# 獲取第page頁的Page實例對象
books_page = self.paginator.page(self.currentPage)
# 獲取所有圖書類型
bookTypes = BookType.objects.all()
# 構造模板需要的參數
context = {

'bookTypes': bookTypes,
'books_page': books_page,
'barcode': barcode,
'bookName': bookName,
'publishDate': publishDate,
'bookTypeObj_bookTypeId': int(bookTypeObj_bookTypeId),
'currentPage': self.currentPage,
'totalPage': self.totalPage,
'recordNumber': self.recordNumber,
'startIndex': self.startIndex,
'pageList': self.pageList,
}
# 渲染模板界面
return render(request, 'Book/book_frontquery_result.html', context)
class FrontShowView(View): # 前台顯示圖片詳情頁
def get(self, request, barcode):
bookTypes = BookType.objects.all()
# 查詢需要顯示的圖書對象
book = Book.objects.get(barcode=barcode)
context = {

'bookTypes': bookTypes,
'book': book
}
# 渲染模板顯示
return render(request, 'Book/book_frontshow.html', context)
class UpdateView(BaseView): # Ajax方式圖書更新
def get(self, request, barcode):
# GET方式請求查詢圖書對象並返回圖書json格式
book = Book.objects.get(barcode=barcode)
return JsonResponse(book.getJsonObj())
def post(self, request, barcode):
# POST方式提交圖書修改信息更新到數據庫
book = Book.objects.get(barcode=barcode)
book.bookName = request.POST.get('book.bookName')
book.bookTypeObj = BookType.objects.get(bookTypeId=int(request.POST.get('book.bookTypeObj.bookTypeId')))
book.price = float(request.POST.get('book.price'))
book.count = int(request.POST.get('book.count'))
book.publishDate = request.POST.get('book.publishDate')
book.publish = request.POST.get('book.publish')
try:
bookPhotoName = self.uploadImageFile(request, 'book.bookPhoto')
except ImageFormatException as ife:
return JsonResponse({
'success': False, 'message': ife.error})
if bookPhotoName != 'img/NoImage.jpg':
book.bookPhoto = bookPhotoName
book.bookDesc = request.POST.get('book.bookDesc')
bookFileName = self.uploadCommonFile(request, 'book.bookFile')
if bookFileName != 'file/NoFile.jpg':
book.bookFile = bookFileName
book.save()
return JsonResponse({
'success': True, 'message': '保存成功'})
class AddView(BaseView): # 後台添加圖書
def primaryKeyExist(self, barcode): # 判斷主鍵是否存在
try:
Book.objects.get(barcode=barcode)
return True
except Book.DoesNotExist:
return False
def get(self, request):
# 獲取所有圖書類型
bookTypes = BookType.objects.all()
context = {

'bookTypes': bookTypes,
}
# 渲染顯示模板界面
return render(request, 'Book/book_add.html', context)
def post(self, request):
# POST方式處理圖書添加業務
barcode = request.POST.get('book.barcode')
if self.primaryKeyExist(barcode):
return JsonResponse({
'success': False, 'message': '圖書條形碼已經存在'})
# 新建一個圖書對象然後收集圖書參數
book = Book()
book.barcode = barcode
book.bookName = request.POST.get('book.bookName')
book.bookTypeObj = BookType.objects.get(bookTypeId=int(request.POST.get('book.bookTypeObj.bookTypeId')))
book.price = float(request.POST.get('book.price'))
book.count = int(request.POST.get('book.count'))
book.publishDate = request.POST.get('book.publishDate')
book.publish = request.POST.get('book.publish')
try:
book.bookPhoto = self.uploadImageFile(request, 'book.bookPhoto')
except ImageFormatException as ife:
return JsonResponse({
'success': False, 'message': ife.error})
book.bookDesc = request.POST.get('book.bookDesc')
book.bookFile = self.uploadCommonFile(request, 'book.bookFile')
book.save() # 這裡提交更新到數據庫
return JsonResponse({
'success': True, 'message': '保存成功'})
class BackModifyView(BaseView): # 後台更新圖書
def get(self, request, barcode):
context = {
"barcode": barcode}
return render(request, 'Book/book_modify.html', context)
class ListView(BaseView): # 後台圖書列表
def get(self, request):
# 使用模板
return render(request, 'Book/book_query_result.html')
def post(self,request):
# 獲取當前要顯示第幾頁和每頁幾條數據
self.getPageAndSize(request)
# 收集查詢參數
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# 然後條件組合查詢過濾
books = Book.objects.all()
if barcode != '':
books = books.filter(barcode__contains=barcode)
if bookName != '':
books = books.filter(bookName__contains=bookName)
if publishDate != '':
books = books.filter(publishDate__contains=publishDate)
if bookTypeObj_bookTypeId != '0':
books = books.filter(bookTypeObj=bookTypeObj_bookTypeId)
# 利用Paginator對查詢結果集分頁
self.paginator = Paginator(books, self.pageSize)
# 計算總的頁碼數,要顯示的頁碼列表,總記錄等
self.calculatePages()
# 獲取第page頁的Page實例對象
books_page = self.paginator.page(self.currentPage)
# 查詢的結果集轉換為列表
bookList = []
for book in books_page:
book = book.getJsonObj()
bookList.append(book)
# 構造模板頁面需要的參數
book_res = {

'rows': bookList,
'total': self.recordNumber,
}
# 渲染模板頁面顯示
return JsonResponse(book_res, json_dumps_params={
'ensure_ascii':False})
class DeletesView(BaseView): # 刪除圖書信息
def get(self, request):
return self.handle(request)
def post(self, request):
return self.handle(request)
def handle(self, request):
barcodes = self.getStrParam(request, 'barcodes')
barcodes = barcodes.split(',')
count = 0
try:
for barcode in barcodes:
Book.objects.get(barcode=barcode).delete()
count = count + 1
message = '%s條記錄刪除成功!' % count
success = True
except Exception as e:
message = '數據庫刪除發生錯誤!'
success = False
return JsonResponse({
"success": success, "message": message})
class OutToExcelView(BaseView): # 導出圖書信息到excel並下載
def get(self,request):
# 收集查詢參數
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# 然後條件組合查詢過濾
books = Book.objects.all()
if barcode != '':
books = books.filter(barcode__contains=barcode)
if bookName != '':
books = books.filter(bookName__contains=bookName)
if publishDate != '':
books = books.filter(publishDate__contains=publishDate)
if bookTypeObj_bookTypeId != '0':
books = books.filter(bookTypeObj=bookTypeObj_bookTypeId)
#將查詢結果集轉換成列表
bookList = []
for book in books:
book = book.getJsonObj()
bookList.append(book)
# 利用pandas實現數據的導出功能
pf = pd.DataFrame(bookList)
# 設置要導入到excel的列
columns_map = {

'barcode': '圖書條形碼',
'bookName': '圖書名稱',
'bookTypeObj': '圖書類別',
'price': '圖書價格',
'count': '圖書數量',
'publishDate': '出版日期',
'publish': '出版社',
}
pf = pf[columns_map.keys()]
pf.rename(columns=columns_map, inplace=True)
# 將空的單元格替換為空字符
pf.fillna('', inplace=True)
#設定文件名和導出路徑
filename = 'books.xlsx'
# 這個路徑可以在settings中設置也可以直接手動輸入
root_path = settings.MEDIA_ROOT + '/output/'
file_path = os.path.join(root_path, filename)
pf.to_excel(file_path, encoding='utf-8', index=False)
# 將生成的excel文件輸出到網頁下載
file = open(file_path, 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="books.xlsx"'
return response

完整程序代碼下載:Python基於mysql+Django框架圖書管理系統源代碼(含mysql文件)
更多Python源代碼請關注公眾號:Python代碼大全。


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved