简易图书管理系统
创建Django项目
1.pycharm新建Django项目
项目名bms2
创建应用app01
2.修改settings.py
MIDDLEWARE注释'django.middleware.csrf.CsrfViewMiddleware'
TEMPLATES修改 'DIRS': [os.path.join(BASE_DIR, 'templates')],
文件末尾添加:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
3.bms2目录下创建static,并添加bootstrap和jquery文件
4.手动MySQL创建bms2库
CREATE DATABASE bms2
5.settings.py配置MySQL数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bms2',
'HOST': '127.0.0.1',
'USER': 'root',
'PASSWORD': '123456',
'PORT': 3306,
'CHARSET': 'utf8'
}
}
准备数据
1.models.py 模型层中添加
class Book(models.Model):
"""图书表"""
# 书名
title = models.CharField(max_length=32)
# 书价
price = models.DecimalField(max_digits=8, decimal_places=2)
# 出版时间
publish_time = models.DateField(auto_now_add=True)
# 出版社 外键 一对多
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
# 作者 外检 多对多
authors = models.ManyToManyField(to='Author')
def __str__(self):
return f'图书对象:{self.title}'
class Publish(models.Model):
"""出版社表"""
# 出版社名
name = models.CharField(max_length=32)
# 出版社地址
address = models.CharField(max_length=32)
def __str__(self):
return f'出版社对象:{self.name}'
class Author(models.Model):
"""作者表"""
# 作者名
name = models.CharField(max_length=32)
# 作者年龄
age = models.IntegerField()
# 作者详情 外键 一对一
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
def __str__(self):
return f'作者对象"{self.name}'
class AuthorDetail(models.Model):
"""作者详情表"""
# 手机号
phone = models.BigIntegerField()
# 住址
address = models.CharField(max_length=64)
def __str__(self):
return f'作者详情手机号:{self.phone}'
2.迁移数据
1.将models中有关数据库的操作记录下来(migrations文件夹)
python3 manage.py makemigrations
2.将操作真正影响到数据库中
python3 manage.py migrate
3.手动添加数据
'''authordetail表'''添加 110,北京市 120,南京市 130,东京市
'''author表'''添加 小北,18,1 小南,19,2 小东,20,3
'''publish表'''添加 北方出版社,北京市 南方出版社,南京市 东方出版社,东京市
'''book表'''添加 小白自传,99.99,2023-05-01,1 小南自传,199.99,2023-04-30,2 小东自传,299.99,2023-0429,3
'''book_authors'''添加 1,1 2,1 2,2 3,1 3,2 3,3
home页面
1.总路由设置
# bms2下的urls.py中修改
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('bms/', include('app01.urls'))
]
2.app01下创建ursl.py
from django.urls import path, re_path
from app01 import views
urlpatterns = [
# home页面
path('home/', views.home, name='app01_home_view'),
]
3.app01下修改views.py
from django.shortcuts import render, HttpResponse, redirect, reverse
def home(requst):
return render(requst, 'home.html')
4.templates下创建home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% block css %}
{% load static %}
<script src="{% static 'jquery.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
<script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
{% endblock %}
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">BMS</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">图书 <span class="sr-only">(current)</span></a></li>
<li><a href="#">出版社</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">更多 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">高启龙</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">后台管理 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<div class="col-md-2">
<div class="list-group">
<a href="" class="list-group-item active">首页</a>
<a href="" class="list-group-item">图书列表</a>
<a href="#" class="list-group-item">出版社列表</a>
<a href="#" class="list-group-item">作者列表</a>
<a href="#" class="list-group-item">更多操作</a>
</div>
</div>
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">图书管理系统</h3>
</div>
<div class="panel-body">
{% block content %}
<div class="jumbotron">
<h1>高启龙的图书平台</h1>
<p>赶紧查阅</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">更多精彩</a></p>
</div>
<div class="row">
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="https://img1.baidu.com/it/u=3811388264,3978135003&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889"
alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
class="btn btn-default"
role="button">Button</a>
</p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="https://img2.baidu.com/it/u=759928418,2104136798&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889"
alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
class="btn btn-default"
role="button">Button</a>
</p>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="https://img2.baidu.com/it/u=2286741612,2446697558&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889"
alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#"
class="btn btn-default"
role="button">Button</a>
</p>
</div>
</div>
</div>
</div>
{% endblock %}
</div>
</div>
</div>
</div>
{% block js %}
{% endblock %}
</body>
</html>
booklist页面
1.app01下修改urls.py
path('booklist/', views.book_list, name='app01_book_list_view'),
2.app02下修改views.py
def book_list(request):
# select_related(orm优化查询),只查询1次数据库,order_by根据pk升序排序
book_queryset = models.Book.objects.select_related('publish').order_by('pk')
return render(request, 'booklist.html', locals())
3.templates下创建booklist.html文件
{% extends 'home.html' %}
{% block content %}
<h1 class="text-center">图书列表</h1>
<a href="" class="btn btn-success">添加书籍</a>
<table class="table table-hover table-striped">
<thead>
<tr>
<th>序号</th>
<th>书名</th>
<th>价格</th>
<th>日期</th>
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book_obj in book_queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book_obj.title }}</td>
<td>{{ book_obj.price }}</td>
<td>{{ book_obj.publish_time|date:'Y-m-d' }}</td>
<td>{{ book_obj.publish.name }}</td>
<td>
{% for author_obj in book_obj.authors.all %}
{% if forloop.last %}
<span>{{ author_obj.name }}</span>
{% else %}
<span>{{ author_obj.name }},</span>
{% endif %}
{% endfor %}
</td>
<td>
<a href="" class="btn btn-primary btn-xs">编辑</a>
<a href="" class="btn btn-danger btn-xs delBtn">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
4.templates下修改home.html文件
<a href="{% url 'app01_home_view' %}" class="list-group-item active">首页</a>
<a href="{% url 'app01_book_list_view' %}" class="list-group-item">图书列表</a>
bookadd页面
1.app01下修改urls.py
path('bookadd/', views.book_add, name='app01_book_add_view'),
2.app02下修改views.py
def book_add(request):
if request.method == 'POST':
# 获取html上的数据
title = request.POST.get('title')
price = request.POST.get('price')
publish_time = request.POST.get('publish_time')
publish_id = request.POST.get('publish_id')
author_list = request.POST.getlist('authors_list')
# 添加数据
book_obj = models.Book.objects.create(
title=title,
price=price,
publish_time=publish_time,
publish_id=publish_id
)
# 外键表添加数据
book_obj.authors.add(*author_list)
return redirect(reverse('app01_book_list_view'))
# 查询出版社
publish_queryset = models.Publish.objects.all()
# 查询作者
author_queryset = models.Author.objects.all()
return render(request, 'bookadd.html', locals())
3.templates下创建booklist.html文件
{% extends 'home.html' %}
{% block content %}
<h1 class="text-center">图书列表</h1>
<a href="" class="btn btn-success">添加书籍</a>
<table class="table table-hover table-striped">
<thead>
<tr>
<th>序号</th>
<th>书名</th>
<th>价格</th>
<th>日期</th>
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book_obj in book_queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book_obj.title }}</td>
<td>{{ book_obj.price }}</td>
<td>{{ book_obj.publish_time|date:'Y-m-d' }}</td>
<td>{{ book_obj.publish.name }}</td>
<td>
{% for author_obj in book_obj.authors.all %}
{% if forloop.last %}
<span>{{ author_obj.name }}</span>
{% else %}
<span>{{ author_obj.name }},</span>
{% endif %}
{% endfor %}
</td>
<td>
<a href="" class="btn btn-primary btn-xs">编辑</a>
<a href="" class="btn btn-danger btn-xs delBtn">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
4.templates下修改booklist.html文件
<a href="{% url 'app01_book_add_view' %}" class="btn btn-success">添加书籍</a>
bookedit页面
1.app01下修改urls.py
path('bookedit/<int:edit_pk>/', views.book_edit, name='app01_book_edit_view'),
2.app02下修改views.py
def book_edit(request, edit_pk):
edit_obj = models.Book.objects.filter(pk=edit_pk).first()
if request.method == 'POST':
# 获取html上的数据
title = request.POST.get('title')
price = request.POST.get('price')
publish_time = request.POST.get('publish_time')
publish_id = request.POST.get('publish_id')
authors_list = request.POST.getlist('authors_list')
models.Book.objects.filter(pk=edit_pk).update(
title=title,
price=price,
publish_time=publish_time,
publish_id=publish_id
)
# 外键表修改数据
edit_obj.authors.set(authors_list)
return redirect(reverse('app01_book_list_view'))
# 查询出版社
publish_queryset = models.Publish.objects.all()
# 查询作者
author_queryset = models.Author.objects.all()
# 传给编辑页面给用户查看并修改
return render(request, 'bookedit.html', locals())
3.templates下创建booklist.html文件
<h1 class="text-center">书籍添加</h1>
<form action="{% url 'app01_book_edit_view' edit_obj.pk %}" method="post">
<p>书名:
<input type="text" name="title" class="form-control" value="{{ edit_obj.title }}">
</p>
<p>价格:
<input type="text" name="price" class="form-control" value="{{ edit_obj.price }}">
</p>
<p>日期:
<input type="date" name="publish_time" class="form-control"
value="{{ edit_obj.publish_time|date:'Y-m-d' }}">
</p>
<p>出版社:
<select name="publish_id" id="" class="form-control">
{% for publish_obj in publish_queryset %}
{% if edit_obj.publish == publish_obj %}
<option value="{{ publish_obj.pk }}" selected>{{ publish_obj.name }}</option>
{% else %}
<option value="{{ publish_obj.pk }}">{{ publish_obj.name }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<p>作者:
<select name="authors_list" id="" multiple class="form-control">
{% for author_obj in author_queryset %}
{% if author_obj in edit_obj.authors.all %}
<option value="{{ author_obj.pk }}" selected>{{ author_obj.name }}</option>
{% else %}
<option value="{{ author_obj.pk }}">{{ author_obj.name }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="编辑" class="btn btn-danger btn-block btn-xs">
</form>
4.templates下修改booklist.html文件
<a href="{% url 'app01_book_edit_view' book_obj.pk %}" class="btn btn-primary btn-xs">编辑</a>
bookdelte页面
1.app01下修改urls.py
re_path('^bookdelete/(?P<delete_id>\d+)/', views.book_delete, name='app01_book_delete_view')
2.app02下修改views.py
def book_delete(request, delete_id):
models.Book.objects.filter(pk=delete_id).delete()
return redirect(reverse('app01_book_list_view'))
3.templates下修改booklist.html文件
<a href="{% url 'app01_book_delete_view' book_obj.pk %}" class="btn btn-danger btn-xs delBtn">删除</a>
还需要在最下面添加删除确认框
{% block js %}
<script>
$('.delBtn').click(function () {
let isDel = confirm('你要删除吗')
if (!isDel) {
return false
}
})
</script>
{% endblock %}
添加删除二次确认
首先静态文件目录static下放置jayer文件
1.app02下修改urls.py
re_path('^bookdelete/', views.book_delete, name='app01_book_delete_view'),
2.app02下修改views.py
def book_delete(request):
user_dict = {'code': 200, 'msg': '删除成功'}
pk = request.POST.get('id')
del_obj = models.Book.objects.filter(pk=pk).first()
del_obj.authors.clear()
models.Book.objects.filter(pk=pk).delete()
return JsonResponse(user_dict)
3.templates下修改booklist.html文件
<a href="#" class="btn btn-danger btn-xs delBtn" pk="{{ book_obj.pk }}">删除</a>
以及
{% block js %}
<script src="/static/layer/layer.js"></script>
<script>
$('.delBtn').click(function () {
var id = $(this).attr('pk')
layer.confirm('您确认是否删除?', {
btn: ['确认', '取消'] //按钮
}, function () {
$.ajax({
url: '{% url 'app01_book_delete_view' %}',
type: 'post',
data: {'id': id},
dataType: 'json',
success: function (res) {
if (res.code === 200) {
layer.msg(res.msg, {icon: 1}, function () {
location.reload()
})
}
}
})
},
);
})
</script>
{% endblock %}
标签:obj,name,管理系统,models,request,publish,简易,book,图书
From: https://www.cnblogs.com/ycmyay/p/17383810.html