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

Python library management system source code based on mysql+django framework (including MySQL file)

編輯:Python

The project foreground and background interface templates are written by ourselves , Front desk Bootstrap frame UI, backstage EasyUI frame UI, There is no Django The background management that is generated automatically , Because that backstage is so ugly , Hideously ugly ! The whole project is mainly responsible for adding book information , modify , Combine multiple query conditions , Delete . Although the system function is not very complicated , But this is a good learning case , Including the design of common fields , Like strings , floating-point , integer , Date type , Picture type , Rich text string type , File type and drop-down box foreign key association type , It includes all the field types required for commercial project design , Kill all commercial system design principles ! Of course, it is also the best choice for learning , Good things are worth sharing , Strongly recommend . The background login user name and password are a.
System entity objects :
Book types : Book category , Category name , Number of days available for borrowing
The book : Book bar code , The name of the book , Category of books , The book price , stock , Publication date , Press. , Pictures of books , Book Introduction , Books and documents .
Screenshot of program operation


Core code

""" 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', # Homepage module 
'apps.BookType', # Book classification module 
'apps.Book', # Book information module 
'tinymce', # Rich text editor 
]
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/'
# To configure session Storage 
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
# Rich text editor configuration 
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
# For the first page The content of the page 
try:
currentPage = int(currentPage)
except Exception as e:
currentPage = 1
if currentPage > totalPage:
currentPage = totalPage
# For the first page page Page Instance object 
bookTypes_page = paginator.page(currentPage)
startIndex = (currentPage - 1) * pageSize # Calculate the starting sequence number 
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)
# Use templates 
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): # Add foreground books 
def primaryKeyExist(self, barcode): # Determine whether the primary key exists 
try:
Book.objects.get(barcode=barcode)
return True
except Book.DoesNotExist:
return False
def get(self,request):
bookTypes = BookType.objects.all() # Get all book types 
context = {

'bookTypes': bookTypes,
}
# Use templates 
return render(request, 'Book/book_frontAdd.html', context)
def post(self,request):
barcode = request.POST.get('book.barcode') # Determine whether the book barcode exists 
if self.primaryKeyExist(barcode):
return JsonResponse({
'success': False, 'message': ' The book barcode already exists '})
book = Book() # Create a new book object and get the parameters 
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() # Save the book information to the database 
return JsonResponse({
'success': True, 'message': ' Saved successfully '})
class FrontModifyView(BaseView): # The front desk modifies books 
def get(self, request, barcode):
context = {
"barcode": barcode}
return render(request, 'Book/book_frontModify.html', context)
class FrontListView(BaseView): # Front desk book query list 
def get(self, request):
return self.handle(request)
def post(self, request):
return self.handle(request)
def handle(self,request):
self.getCurrentPage(request) # Get the current page to display 
# Next, get the query parameters 
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# Then the condition combination query filters 
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)
# Utilization of query results Paginator paging 
self.paginator = Paginator(book, self.pageSize)
# Calculate the total number of pages , List of page numbers to display , General records, etc 
self.calculatePages()
# For the first page page Page Instance object 
books_page = self.paginator.page(self.currentPage)
# Get all book types 
bookTypes = BookType.objects.all()
# Parameters required to construct the template 
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,
}
# Render template interface 
return render(request, 'Book/book_frontquery_result.html', context)
class FrontShowView(View): # The foreground displays the picture details page 
def get(self, request, barcode):
bookTypes = BookType.objects.all()
# Query the book object to be displayed 
book = Book.objects.get(barcode=barcode)
context = {

'bookTypes': bookTypes,
'book': book
}
# Render template display 
return render(request, 'Book/book_frontshow.html', context)
class UpdateView(BaseView): # Ajax Way Book update 
def get(self, request, barcode):
# GET Method to query the book object and return the book json Format 
book = Book.objects.get(barcode=barcode)
return JsonResponse(book.getJsonObj())
def post(self, request, barcode):
# POST Submit the book modification information and update it to the database 
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': ' Saved successfully '})
class AddView(BaseView): # Add books in the background 
def primaryKeyExist(self, barcode): # Determine whether the primary key exists 
try:
Book.objects.get(barcode=barcode)
return True
except Book.DoesNotExist:
return False
def get(self, request):
# Get all book types 
bookTypes = BookType.objects.all()
context = {

'bookTypes': bookTypes,
}
# Render display template interface 
return render(request, 'Book/book_add.html', context)
def post(self, request):
# POST Method to handle the book addition business 
barcode = request.POST.get('book.barcode')
if self.primaryKeyExist(barcode):
return JsonResponse({
'success': False, 'message': ' The book barcode already exists '})
# Create a new book object and collect Book parameters 
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() # Here, submit the update to the database 
return JsonResponse({
'success': True, 'message': ' Saved successfully '})
class BackModifyView(BaseView): # Background update books 
def get(self, request, barcode):
context = {
"barcode": barcode}
return render(request, 'Book/book_modify.html', context)
class ListView(BaseView): # Backstage book list 
def get(self, request):
# Use templates 
return render(request, 'Book/book_query_result.html')
def post(self,request):
# Get the current page to be displayed and several pieces of data per page 
self.getPageAndSize(request)
# Collect query parameters 
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# Then the condition combination query filters 
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)
# utilize Paginator Paging the query result set 
self.paginator = Paginator(books, self.pageSize)
# Calculate the total number of pages , List of page numbers to display , General records, etc 
self.calculatePages()
# For the first page page Page Instance object 
books_page = self.paginator.page(self.currentPage)
# The result set of the query is converted to a list 
bookList = []
for book in books_page:
book = book.getJsonObj()
bookList.append(book)
# Parameters required to construct template pages 
book_res = {

'rows': bookList,
'total': self.recordNumber,
}
# The render template page displays 
return JsonResponse(book_res, json_dumps_params={
'ensure_ascii':False})
class DeletesView(BaseView): # Delete book information 
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 Records deleted successfully !' % count
success = True
except Exception as e:
message = ' An error occurred while deleting the database !'
success = False
return JsonResponse({
"success": success, "message": message})
class OutToExcelView(BaseView): # Export book information to excel And download 
def get(self,request):
# Collect query parameters 
barcode = self.getStrParam(request, 'barcode')
bookName = self.getStrParam(request, 'bookName')
publishDate = self.getStrParam(request, 'publishDate')
bookTypeObj_bookTypeId = self.getIntParam(request, 'bookTypeObj.bookTypeId')
# Then the condition combination query filters 
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)
# Convert the query result set into a list 
bookList = []
for book in books:
book = book.getJsonObj()
bookList.append(book)
# utilize pandas Realize the data export function 
pf = pd.DataFrame(bookList)
# Settings to import into excel The column of 
columns_map = {

'barcode': ' Book bar code ',
'bookName': ' The name of the book ',
'bookTypeObj': ' Book category ',
'price': ' The book price ',
'count': ' Number of books ',
'publishDate': ' Publication date ',
'publish': ' Press. ',
}
pf = pf[columns_map.keys()]
pf.rename(columns=columns_map, inplace=True)
# Replace empty cells with empty characters 
pf.fillna('', inplace=True)
# Set the file name and export path 
filename = 'books.xlsx'
# This path can be in settings The settings in can also be entered manually 
root_path = settings.MEDIA_ROOT + '/output/'
file_path = os.path.join(root_path, filename)
pf.to_excel(file_path, encoding='utf-8', index=False)
# The generated excel File output to web page download 
file = open(file_path, 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="books.xlsx"'
return response

Complete program code download :Python be based on mysql+Django Framework library management system source code ( contain mysql file )
more Python Source code, please pay attention to official account. :Python The code of .


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