代码情况
urls.py
C:\Code\BookManagement\BookManagement\urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('management.urls')), # 将management应用的URL设置包含到项目的URL设置中
]
C:\Code\BookManagement\management\urls.py
from django.urls import URLPattern, path
from management import views
from django.views.generic import RedirectView
urlpatterns = [
path('', views.index, name='homepage'),
path('favicon.ico',RedirectView.as_view(url='/static/images/droplet-half.svg')),
path('index/', views.index, name='homepage'),
path('sign_up/', views.sign_up, name='sign_up'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('change_password/', views.change_password, name='change_password'),
path('add_book/', views.add_book, name='add_book'),
path('edit_book', views.edit_book, name='edit_book'),
path('book_list', views.book_list, name='book_list'),
path('error/', views.error, name='error'),
path('add_category/', views.add_category, name='add_category'),
path('edit_category', views.edit_category, name='edit_category'),
path('category_list', views.category_list, name='category_list'),
path('book_detail', views.book_detail, name='book_detail'),
]
models.py
C:\Code\BookManagement\management\models.py
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=128, verbose_name='书籍名称')
author = models.CharField(max_length=64, blank=True, verbose_name='作者')
describe = models.CharField(max_length=64, blank=True, verbose_name='描述')
index = models.CharField(max_length=64, blank=True, verbose_name='目录')
price = models.FloatField(default=0.0, verbose_name='定价')
publish_date = models.DateField(null=True, blank=True, verbose_name='出版日期')
category = models.CharField(
max_length=32, default='未分类', verbose_name='分类'
)
create_datetime = models.DateTimeField(
auto_now_add=True, verbose_name='添加日期'
) # auto_now_add参数自动填充当前时间
def __str__(self): # 定义__str__方法后,在将模型对象作为参数传递给str()函数时会调用该方法返回相应的字符串
return self.name
class Category(models.Model):
parent_category = models.CharField(max_length=32, null=True, blank=True, verbose_name="父类")
category = models.CharField(
max_length=32, verbose_name='分类'
)
settings.py
C:\Code\BookManagement\BookManagement\settings.py
"""
Django settings for BookManagement project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*6g14r6ubexu1v_m(_$rzgucc+v^avme(0&yfpm56tvuh6(mov'
# 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',
'management',
]
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 = 'BookManagement.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 = 'BookManagement.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
views.py
C:\Code\BookManagement\management\views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.contrib.auth.models import User, auth
import email
from xml.etree.ElementTree import tostring
# Create your views here.
def index(request):
if request.user.is_authenticated:
content={
'username':request.user,
}
return render(request, "management/index.html",content)
return render(request, "management/index.html")
def sign_up(request):
if request.method == "POST":
try:
username = request.POST.get('username', '')
password = request.POST.get('password', '')
repassword = request.POST.get('repassword', '')
email = request.POST.get('email', '')
if password == '' or repassword == '':
state = '口令都不填的么'
elif password != repassword:
state = '你这两遍口令填的不同啊'
elif username == '':
state = '用户名格式错误'
elif email == '':
state = '邮箱是要填的呦'
else:
if User.objects.filter(username=username):
state = '换个用户名,这个已经被占用了'
else:
new_user = User.objects.create_user(
username=username, password=password, email=email)
new_user.save()
state = '注册成功'
user = auth.authenticate(username=username, password=password)
auth.login(request, user)
return redirect("/index/")
except:
state = '注册失败'
finally:
return HttpResponse(state)
if request.user.is_authenticated:
return redirect("/index")
return render(request, "management/sign_up.html")
def login(request):
if request.method == "POST":
username = request.POST.get('username', '')
password = request.POST.get('password', '')
if username and password:
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
state = '登录成功'
else:
state = '用户不存在或口令错误'
else:
state = '请输入用户名和口令'
return HttpResponse(state)
if request.user.is_authenticated:
return redirect("/index")
return render(request, "management/login.html")
def logout(request):
auth.logout(request)
return redirect("/index/")
def change_password(request):
if request.user.is_authenticated:
if request.method == "POST":
user = request.user
password = request.POST.get('password', '')
newpassword = request.POST.get('newpassword', '')
confirmpassword = request.POST.get('confirmpassword', '')
if user.check_password(password):
if not newpassword:
state = '新口令要填的呦'
elif newpassword != confirmpassword:
state = '两次口令输入的不同呦'
else:
user.set_password(newpassword)
user.save()
state = '修改成功'
else:
state = '口令输错了'
return HttpResponse(state)
content={
'username':request.user,
}
return render(request, "management/change_password.html",content)
return render(request, "management/change_password.html")
from management import models
import math
def book_list(request):
if request.user.is_authenticated:
if request.method == "GET":
search=request.GET.get('search','')
page=int(request.GET.get('page',1))
book_list = models.Book.objects.filter(name__regex=search).only('id','name','author','publish_date','price')[(15*(page-1)):15*page-1]
book_list_count = math.ceil(models.Book.objects.filter(name__regex=search).only('id').count()/15)
lastpage = int(page-1)
nextpage = int(page+1)
if lastpage <= 0 :
lastpage = 1
if nextpage > int(book_list_count):
nextpage = int(book_list_count)
content={
'username':request.user,
'book_list':book_list,
'lastpage':lastpage,
'nextpage':nextpage,
'search':search,
}
return render(request,"management/book_list.html",content)
return render(request,"management/book_list.html")
from management import models
def add_book(request):
if request.user.is_authenticated:
if request.method == "GET":
category_list = models.Category.objects.all().only('category')
content = {
'username':request.user,
'category_list':category_list,
}
return render(request,"management/add_book.html",content)
if request.method == "POST":
try:
name = cleandata.TypeChar(request.POST.get('name', ''))
author = cleandata.TypeChar(request.POST.get('author', ''))
price = cleandata.TypeFloat(request.POST.get('price', ''))
publish_date = cleandata.TypeDate(request.POST.get('publish_date', ''))
category = cleandata.TypeChar(request.POST.get('category', ''))
create_datetime = cleandata.TypeDatetime(request.POST.get('create_datetime', ''))
if name == "":
state='书名都不填的么'
elif author == "":
state='作者都不填的么'
elif price == "":
state='价格都不填的么'
elif publish_date == "":
state='出版日期都不填的么'
elif category == "":
state='类型都不选的么'
else:
if models.Book.objects.filter(name=name,author=author):
state='已经添加过这本书籍了'
else:
models.Book.objects.create(
name = name,
author = author,
price = price,
publish_date = publish_date,
category = category,
create_datetime = create_datetime,
)
state='添加成功'
except:
state='添加失败'
finally:
return HttpResponse(state)
return render(request,"management/add_book.html")
def edit_book(request):
if request.user.is_authenticated:
if request.method == "GET":
id = request.GET.get('id','')
if id:
book = models.Book.objects.get(id=id)
category_list = models.Category.objects.all().only('category')
content = {
'username':request.user,
'category_list':category_list,
'book':book,
}
else:
return redirect("/add_book/")
return render(request,"management/edit_book.html",content)
elif request.method == "POST":
try:
id = request.POST.get('id', '')
name = cleandata.TypeChar(request.POST.get('name', ''))
author = cleandata.TypeChar(request.POST.get('author', ''))
describe = cleandata.TypeChar(request.POST.get('describe', ''))
index = cleandata.TypeChar(request.POST.get('index', ''))
price = cleandata.TypeFloat(request.POST.get('price', ''))
publish_date = cleandata.TypeDate(request.POST.get('publish_date', ''))
category = cleandata.TypeChar(request.POST.get('category', ''))
if name == "":
state='书名都不填的么'
elif author == "":
state='作者都不填的么'
elif price == "":
state='价格都不填的么'
elif publish_date == "":
state='出版日期都不填的么'
elif category == "":
state='类型都不选的么'
else:
models.Book.objects.filter(id=id).update(
name = name,
author = author,
describe = describe,
index = index,
price = price,
publish_date = publish_date,
category = category,
)
state='编辑成功'
except:
state='编辑失败'
finally:
return HttpResponse(state)
return render(request,"management/edit_book.html")
def error(request):
return render(request,"error.html")
def add_category(request):
if request.user.is_authenticated:
if request.method == "POST":
try:
parent_category = cleandata.TypeChar(request.POST.get('parent_category', ''))
category = cleandata.TypeChar(request.POST.get('category',''))
if category:
if models.Book.objects.filter(category=category):
state='已经添加过这个子类了'
else:
new_category = models.Category (
parent_category = parent_category,
category = category,
)
new_category.save()
state='添加成功'
else:
state='子类没有填内容哦'
except:
state='添加失败'
finally:
return HttpResponse(state)
category_list = models.Category.objects.all().only('category')
content={
'username':request.user,
'category_list':category_list,
}
return render(request, "management/add_category.html",content)
return render(request,"management/add_category.html")
def edit_category(request):
if request.user.is_authenticated:
if request.method == "GET":
id = request.GET.get('id','')
if id:
category = models.Category.objects.get(id=id)
category_list = models.Category.objects.all().only('category')
content={
'username':request.user,
'category_list':category_list,
'category':category,
}
else:
return redirect("/add_category/")
return render(request,"management/edit_category.html",content)
elif request.method == "POST":
try:
id = request.POST.get('id', '')
parent_category = cleandata.TypeChar(request.POST.get('parent_category', ''))
category = cleandata.TypeChar(request.POST.get('category',''))
if category:
if models.Category.objects.filter(parent_category=parent_category,category=category):
state='已经添加过这个子类了'
else:
a=models.Category.objects.filter(id=id).update(parent_category=parent_category,category=category)
print("---------------------------------------")
print(a)
state='编辑成功'
else:
state='子类没有填内容哦'
except:
state='编辑失败'
finally:
return HttpResponse(state)
else:
return redirect("/error/")
def category_list(request):
if request.user.is_authenticated:
if request.method == "GET":
search=request.GET.get('search','')
page=int(request.GET.get('page',1))
category_list = models.Category.objects.filter(category__regex=search).only('id','parent_category','category')[(15*(page-1)):15*page-1]
category_list_count =math.ceil(models.Category.objects.filter(category__contains=search).only('id').count()/15)
lastpage = int(page-1)
nextpage = int(page+1)
if lastpage <= 0 :
lastpage = 1
if nextpage > int(category_list_count):
nextpage = int(category_list_count)
content={
'username':request.user,
'category_list':category_list,
'lastpage':lastpage,
'nextpage':nextpage,
'search':search,
}
return render(request,"management/category_list.html",content)
return render(request,"management/category_list.html")
def book_detail(request):
if request.user.is_authenticated:
if request.method == "GET":
id = cleandata.TypeNum(request.GET.get('id', ''))
if id != '' and id != 0:
book = models.Book.objects.get(id=id)
content = {
'book':book,
}
return render(request,"management/book_detail.html",content)
return render(request,"management/book_detail.html")
class cleandata():
def TypeNum(data):
try:
return int(data)
except:
return int(0)
def TypeFloat(data):
try:
return float(data)
except:
return float(0.00)
def TypeEmail(data):
try:
return email(data)
except:
return email("@163.com")
def TypeUsername(data):
try:
return tostring(data).replace(["'","<",">","#"],"")
except:
return None
def TypeChar(data):
try:
return data.replace("'","")
except:
return None
def TypeDate(data):
try:
return data
except:
return None
def TypeDatetime(data):
try:
return data
except:
return None
templates
add_book.html
{% extends "management/navbar.html" %}
{% block title %}添加书籍信息{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">添加书籍</h1>
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_name" required name="name" autofocus placeholder="书名"
autocomplete="off">
<label for="id_name">书名</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_author" required name="author" placeholder="作者"
autocomplete="off">
<label for="id_author">作者</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="id_category" aria-label="类型" name="category">
<option value=""></option>
{% for categoryselection in category_list %}
<option value="{{categoryselection.category}}">{{categoryselection.category}}</option>
{% endfor %}
</select>
<label for="id_category">类型</label>
</div>
<div class="form-floating mb-3">
<input type="number" step="0.01" min="0" maxlength="200" class="form-control" id="id_price" required
name="price" placeholder="价格" autocomplete="off">
<label for="id_price">价格</label>
</div>
<div class="form-floating mb-3">
<input type="date" class="form-control" id="id_publish_date" required name="publish_date"
placeholder="出版日期" autocomplete="off">
<label for="id_publish_date">出版日期</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">提交</button>
<hr class="my-4">
<div class="form-floating mb-3">
<div class="alert"
style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;">
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'name': $('#id_name').val(),
'author': $('#id_author').val(),
'category': $('#id_category').val(),
'price': $('#id_price').val(),
'publish_date': $('#id_publish_date').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/add_book/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'name': $('#id_name').val(),
'author': $('#id_author').val(),
'category': $('#id_category').val(),
'price': $('#id_price').val(),
'publish_date': $('#id_publish_date').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/add_book/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
add_category.html
C:\Code\BookManagement\templates\management\add_category.html
{% extends "management/navbar.html" %}
{% block title %}添加书籍分类{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">添加分类</h1>
{% csrf_token %}
<div class="form-floating mb-3">
<select class="form-select" id="id_parent_category" aria-label="父类" name="parent_category">
<option value=""></option>
{% for categoryselection in category_list %}
<option value="{{categoryselection.category}}">{{categoryselection.category}}</option>
{% endfor %}
</select>
<label for="id_category">父类</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_category" required name="category" autofocus
placeholder="子类" autocomplete="off">
<label for="id_category">子类</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">提交</button>
<hr class="my-4">
<div class="form-floating mb-3">
<div class="alert"
style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;">
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'parent_category': $('#id_parent_category').val(),
'category': $('#id_category').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/add_category/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'parent_category': $('#id_parent_category').val(),
'category': $('#id_category').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/add_category/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
book_detail.html
C:\Code\BookManagement\templates\management\book_detail.html
{% extends "management/navbar.html" %}
{% block title %}书籍详情{% endblock %}
{% block content %}
<h1 class="visually-hidden">Heroes examples</h1>
<div class="px-4 py-5 my-5 text-center">
<h1 class="display-5 fw-bold">{{book.name}}</h1>
<div class="col-lg-6 mx-auto">
<p class="lead mb-4"></p>
<p class="lead mb-4"></p>
<p class="lead mb-4" style="text-align: left;">作者:{{book.author}}</p>
<p class="lead mb-4" style="text-align: left;">分类:{{book.category}}</p>
<p class="lead mb-4" style="text-align: left;">简介:{{book.describe}}</p>
<p class="lead mb-4" style="text-align: right;">价格:{{book.price}}</p>
<p class="lead mb-4" style="text-align: right;">出版日期:{{book.publish_date}}</p>
</div>
</div>
{% endblock %}
book_list.html
C:\Code\BookManagement\templates\management\book_list.html
{% extends "management/navbar.html" %}
{% block title %}书籍列表{% endblock %}
{% block content %}
<nav class="py-2 bg-light border-bottom">
<div class="container d-flex flex-wrap">
<ul class="nav me-auto">
<li class="nav-item" id="id_category_all"><a href="/add_book/" class="nav-link link-dark px-2">添加书籍</a></li>
</ul>
<ul class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" id="id_search" autocomplete="off" value="{{search}}" autofocus>
<button class="btn btn-outline-success" type="submit" id="id_submit" style="width: 80px;">搜索</button>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-hover" style="text-align: center;">
{% csrf_token %}
<thead>
<tr>
<th width="8%">#</th>
<th hidden>书籍ID</th>
<th width="50%">书名</th>
<th width="12%">作者</th>
<th width="11%">出版日期</th>
<th width="10%">定价</th>
<th width="9%">
</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<th style="font-weight:normal;">{{forloop.counter}}</th>
<th hidden>{{book.id}}</th>
<th><a href="/book_detail?id={{book.id}}"
style="text-decoration:none;color: black;">{{book.name}}</a>
</th>
<th>{{book.author}}</th>
<th style="font-weight:normal;">{{book.publish_date}}
<th style="font-weight:normal;">{{book.price}}</th>
<th>
<a href="/edit_book?id={{book.id}}" id="id_edit_book" style="color:black;text-decoration:none">编辑</a>
</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item">
<a class="page-link" href="/book_list?page={{lastpage}}" style="color: black;">上一页</a>
</li>
<li class="page-item">
<a class="page-link" href="/book_list?page={{nextpage}}" style="color: black;">下一页</a>
</li>
</ul>
</nav>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
$.ajax({
url: '',
type: 'get',
data: {
'search': $('#id_search').val(),
},
success: function () {
window.location.replace("/book_list?search=" + document.getElementById("id_search").value);
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if ((e.keyCode == 9) || (e.keyCode == 32) || (e.keyCode == 13)) { //当按键为Tab、Enter、Space时执行操作
$.ajax({
url: '',
type: 'get',
data: {
'search': $('#id_search').val(),
},
success: function () {
window.location.replace("/book_list?search=" + document.getElementById("id_search").value);
}
})
}
})
</script>
{% endblock %}
category_list.html
C:\Code\BookManagement\templates\management\category_list.html
{% extends "management/navbar.html" %}
{% block title %}书籍分类列表{% endblock %}
{% block content %}
<nav class="py-2 bg-light border-bottom">
<div class="container d-flex flex-wrap">
<ul class="nav me-auto">
<li class="nav-item" id="id_add_category"><a href="/add_category/" class="nav-link link-dark px-2">添加分类</a>
</li>
</ul>
<ul class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" id="id_search" autocomplete="off" value="{{search}}" autofocus>
<button class="btn btn-outline-success" type="submit" id="id_submit" style="width: 80px;">搜索</button>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-hover" style="text-align: center;">
{% csrf_token %}
<thead>
<tr>
<th width="8%">#</th>
<th hidden>分类ID</th>
<th width="12%">父类</th>
<th width="50%">分类</th>
<th width="9%">
</th>
</tr>
</thead>
<tbody>
{% for category in category_list %}
<tr>
<th style="font-weight:normal;">{{forloop.counter}}</th>
<th hidden>{{category.id}}</th>
<th>{{category.parent_category}}</th>
<th>{{category.category}}</th>
<th>
<a href="/edit_category?id={{category.id}}" id="id_edit_category" style="color:black;text-decoration:none">编辑</a>
</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item">
<a class="page-link" href="/category_list?page={{lastpage}}" style="color: black;">上一页</a>
</li>
<li class="page-item">
<a class="page-link" href="/category_list?page={{nextpage}}" style="color: black;">下一页</a>
</li>
</ul>
</nav>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
$.ajax({
url: '',
type: 'get',
data: {
'search': $('#id_search').val(),
},
success: function () {
window.location.replace("/category_list?search=" + document.getElementById("id_search").value);
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if ((e.keyCode == 9) || (e.keyCode == 32) || (e.keyCode == 13)) { //当按键为Tab、Enter、Space时执行操作
$.ajax({
url: '',
type: 'get',
data: {
'search': $('#id_search').val(),
},
success: function () {
window.location.replace("/category_list?search=" + document.getElementById("id_search").value);
}
})
}
})
</script>
{% endblock %}
change_password.html
C:\Code\BookManagement\templates\management\change_password.html
{% extends "management/navbar.html" %}
{% block title %}修改口令{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto col-lg-5">
<div class="p-4 p-md-5 border rounded-3 bg-light">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">修改口令</h1>
{% csrf_token %}
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_password" required name="password" autofocus placeholder="OldPassword" autocomplete="off">
<label for="id_password">OldPassword</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_newpassword" required name="newpassword" placeholder="NewPassword" autocomplete="off">
<label for="id_newpassword">NewPassword</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_confirmpassword" required name="confirmpassword" placeholder="ConfirmPassword" autocomplete="off">
<label for="id_confirmpassword">ConfirmPassword</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">确认修改</button>
<hr class="my-4">
<small class="text-muted">Quick Quick Change Password.</small>
<div class="form-floating mb-3">
<div class="alert" style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;"></div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url:'',
type:'post',
data:{
'password':$('#id_password').val(),
'newpassword':$('#id_newpassword').val(),
'confirmpassword':$('#id_confirmpassword').val(),
'csrfmiddlewaretoken': csrf,
},
success:function(state) {
if (state == '修改成功') {
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url:'',
type:'post',
data:{
'password':$('#id_password').val(),
'newpassword':$('#id_newpassword').val(),
'confirmpassword':$('#id_confirmpassword').val(),
'csrfmiddlewaretoken': csrf,
},
success:function(state) {
if (state == '修改成功') {
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
edit_book.html
C:\Code\BookManagement\templates\management\edit_book.html
{% extends "management/navbar.html" %}
{% block title %}编辑书籍信息{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto">
<div class="row align-items-center g-lg-5 py-5">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">编辑图书</h1>
{% csrf_token %}
<div class="col-lg-5 text-center text-lg-start">
<div class="form-floating mb-3" hidden>
<input type="text" class="form-control" id="id_id" required name="id"
placeholder="id" autocomplete="off" value="{{book.id}}">
<label for="id_id">id</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_name" required name="name" autofocus placeholder="书名"
autocomplete="off" value="{{book.name}}">
<label for="id_name">书名</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_author" required name="author" placeholder="作者"
autocomplete="off" value="{{book.author}}">
<label for="id_author">作者</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="id_category" aria-label="类型" name="category">
<option value=""></option>
{% for categoryselection in category_list %}
<option value="{{categoryselection.category}}" {% ifequal categoryselection.category book.category %}
selected {% endifequal %}>{{categoryselection.category}}</option>
{% endfor %}
</select>
<label for="id_category">类型</label>
</div>
<div class="form-floating mb-3">
<input type="number" step="0.01" min="0" maxlength="200" class="form-control" id="id_price" required
name="price" placeholder="价格" autocomplete="off" value="{{book.price}}">
<label for="id_price">价格</label>
</div>
<div class="form-floating mb-3">
<input type="date" class="form-control" id="id_publish_date" required name="publish_date"
placeholder="出版日期" autocomplete="off" value="{{book.publish_date}}">
<label for="id_publish_date">出版日期</label>
</div>
</div>
<div class="col-md-10 mx-auto col-lg-7">
<div class="form-floating mb-3">
<textarea type="text" class="form-control" id="id_describe" required name="describe" placeholder="描述" style="height: 150px;"
autocomplete="off">{{book.describe}}</textarea>
<label for="id_describe">描述</label>
</div>
<div class="form-floating mb-3">
<textarea type="text" class="form-control" id="id_index" required name="index" placeholder="目录" style="height: 190px;"
autocomplete="off">{{book.index}}</textarea>
<label for="id_index">目录</label>
</div>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">提交</button>
<hr class="my-4">
<div class="form-floating mb-3">
<div class="alert"
style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;">
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'id': $('#id_id').val(),
'name': $('#id_name').val(),
'author': $('#id_author').val(),
'describe': $('#id_describe').val(),
'index': $('#id_index').val(),
'category': $('#id_category').val(),
'price': $('#id_price').val(),
'publish_date': $('#id_publish_date').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'id': $('#id_id').val(),
'name': $('#id_name').val(),
'author': $('#id_author').val(),
'describe': $('#id_describe').val(),
'index': $('#id_index').val(),
'category': $('#id_category').val(),
'price': $('#id_price').val(),
'publish_date': $('#id_publish_date').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '添加成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
edit_category.html
C:\Code\BookManagement\templates\management\edit_category.html
{% extends "management/navbar.html" %}
{% block title %}编辑书籍分类{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">编辑分类</h1>
{% csrf_token %}
<div class="form-floating mb-3" hidden>
<input type="text" class="form-control" id="id_id" required name="id"
placeholder="id" autocomplete="off" value="{{category.id}}">
<label for="id_id">id</label>
</div>
<div class="form-floating mb-3">
<select class="form-select" id="id_parent_category" aria-label="父类" name="parent_category">
<option value=""></option>
{% for categoryselection in category_list %}
<option value="{{categoryselection.category}}" {% ifequal categoryselection.category category.parent_category %}
selected {% endifequal %}>{{categoryselection.category}}</option>
{% endfor %}
</select>
<label for="id_category">父类</label>
</div>
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_category" required name="category" autofocus
placeholder="子类" autocomplete="off" value="{{category.category}}">
<label for="id_category">子类</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">提交</button>
<hr class="my-4">
<div class="form-floating mb-3">
<div class="alert"
style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;">
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'id': $('#id_id').val(),
'parent_category': $('#id_parent_category').val(),
'category': $('#id_category').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '编辑成功') {
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'id': $('#id_id').val(),
'parent_category': $('#id_parent_category').val(),
'category': $('#id_category').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '编辑成功') {
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
index.html
C:\Code\BookManagement\templates\management\index.html
{% extends "management/navbar.html" %}
{% block title %}主页{% endblock %}
{% block content %}
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<div class="container-fluid py-5">
<h1 class="col-md-10 col-md-offset-1 display-5 fw-bold">欢迎使用图书管理系统</h1>
<p class="col-md-12 col-md-offset-1 fs-4">图书馆管理系统,能进行图书馆管理系统能实测国民经济和企业的各种运行情况;利用过去的数据预测未来;从企业全局出发辅助企业进行管理决策;利用信息控制企业的行为;帮助企业实现其规划目标。<br>
图书馆管理系统合运用了管理科学,系统科学,运筹学,统计学,计算机科学等学科的知识。可以通俗的简化的描述图书馆管理系统的三要素:系统的观点、数学的方法以及计算机的应用。<br>
图书馆管理系统概念结构主要由四大部分组成即信息源、信息处理器、信息用户、信息管理者组成。<br>
</p>
</div>
</div>
</div>
{% endblock %}
login.html
C:\Code\BookManagement\templates\management\login.html
{% extends "management/navbar.html" %}
{% block title %}登录{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-lg-7 text-center text-lg-start">
<h1 class="display-4 fw-bold lh-1 mb-3">欢迎登录图书管理系统</h1>
<p class="col-lg-10 fs-5">
图书馆管理系统,能进行图书馆管理系统能实测国民经济和企业的各种运行情况;利用过去的数据预测未来;从企业全局出发辅助企业进行管理决策;利用信息控制企业的行为;帮助企业实现其规划目标。<br>
图书馆管理系统合运用了管理科学,系统科学,运筹学,统计学,计算机科学等学科的知识。可以通俗的简化的描述图书馆管理系统的三要素:系统的观点、数学的方法以及计算机的应用。<br>
图书馆管理系统概念结构主要由四大部分组成即信息源、信息处理器、信息用户、信息管理者组成。<br>
</p>
</div>
<div class="col-md-10 mx-auto col-lg-5">
<div class="p-4 p-md-5 border rounded-3 bg-light">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_username" required name="username" autofocus placeholder="Uesrname" autocomplete="off">
<label for="id_username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_password" required name="password" placeholder="Password" autocomplete="off">
<label for="id_password">Password</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">登录</button>
<hr class="my-4">
<small class="text-muted">By clicking Login, you agree to the terms of use.</small>
<div class="form-floating mb-3">
<div class="alert" style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;"></div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '登录成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if ((e.keyCode == 9) || (e.keyCode == 32) || (e.keyCode == 13) || ((((e.keyCode == 83)) && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)))) { //当按键为Tab、Enter、Space、Ctrl+S时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: '',
type: 'post',
data: {
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'csrfmiddlewaretoken': csrf,
},
success: function (state) {
if (state == '登录成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
navbar.html
C:\Code\BookManagement\templates\management\navbar.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{% block title%}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}">
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
</head>
<nav class="py-2 bg-light border-bottom fixed-top">
<div class="container d-flex flex-wrap">
<ul class="nav me-auto">
<li class="nav-item" id="homepage"><a href="/index/" class="nav-link link-dark px-2 active"
aria-current="page">主页</a></li>
<li class="nav-item" id="book_list"><a href="/book_list" class="nav-link link-dark px-2">书籍列表</a></li>
<li class="nav-item" id="category_list"><a href="/category_list" class="nav-link link-dark px-2">书籍分类列表</a></li>
</ul>
<ul class="nav">
{% if username %}
<li class="nav-item"><a href="/change_password/" class="nav-link link-dark px-2">{{username}}</a></li>
<li class="nav-item"><a href="/logout/" class="nav-link link-dark px-2">退出</a></li>
{% else %}
<li class="nav-item"><a href="/sign_up/" class="nav-link link-dark px-2">注册</a></li>
<li class="nav-item"><a href="/login/" class="nav-link link-dark px-2">登录</a></li>
{% endif %}
</ul>
</div>
</nav>
<div style="height: 60px;"></div>
<body>
{% block content %}
{% endblock %}
<hr class="featurette-divider">
<footer class="container footer">
<p>© 2022 Company, Inc. All rights reserved.</p>
</footer>
{% block javascript %}
{% endblock %}
</body>
</html>
sign_up.html
C:\Code\BookManagement\templates\management\sign_up.html
{% extends "management/navbar.html" %}
{% block title %}注册{% endblock %}
{% block content %}
<div class="container col-xl-12 col-xxl-12 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto col-lg-5">
<div class="p-4 p-md-10 border rounded-3 bg-light">
<h1 class="display-8 fw-bold lh-1 mb-3" style="text-align: center;">注册</h1>
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="id_username" required name="username" autofocus placeholder="Uesrname" autocomplete="off">
<label for="id_username">Username</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_password" required name="password" placeholder="Password" autocomplete="off">
<label for="id_password">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control" id="id_repassword" required name="repassword" placeholder="rePassword" autocomplete="off">
<label for="id_repassword">rePassword</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control" id="id_email" required name="email" placeholder="Email" autocomplete="off">
<label for="id_email">Email</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit" id="id_submit">注册</button>
<hr class="my-4">
<small class="text-muted">By clicking Sign up, you agree to the terms of use.</small>
<div class="form-floating mb-3">
<div class="alert" style="width:50%;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;text-align: center;overflow: hidden;height: fit-content;font-size:x-small;"></div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
$('#id_submit').click(function () {
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url:'',
type:'post',
data:{
'username':$('#id_username').val(),
'password':$('#id_password').val(),
'repassword':$('#id_repassword').val(),
'email':$('#id_email').val(),
'csrfmiddlewaretoken': csrf,
},
success:function(state) {
if (state == '注册成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
})
document.addEventListener("keydown", function (e) { //获取按键事件
if (e.keyCode == 13) { //当按键为Enter时执行操作
var csrf = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url:'',
type:'post',
data:{
'username':$('#id_username').val(),
'password':$('#id_password').val(),
'repassword':$('#id_repassword').val(),
'email':$('#id_email').val(),
'csrfmiddlewaretoken': csrf,
},
success:function(state) {
if (state == '注册成功') {
$('.alert').html(state).removeClass('alert-danger');
$('.alert').html(state).addClass('alert-success').fadeIn("slow").delay(1500).fadeOut();
window.location.replace("/index/");
}
else {
$('.alert').html(state).addClass('alert-danger').fadeIn("slow").delay(1500).fadeOut();
}
}
})
}
})
</script>
{% endblock %}
error.html
C:\Code\BookManagement\templates\error.html
{% extends "management/navbar.html" %}
{% block title %}404{% endblock %}
{% block content %}
<header class="jumbotron subhead" id="header-base">
<div class="container">
<h1 style="text-align: center;line-height:500px">给你一个错误自己领会</h1>
</div>
</header>
{% endblock %}