models.py ORM数据表
import datetime
import mongoengine
# 继承Document类,为普通文档,如果是EmbeddedDocument类是内嵌文档,DynamicDocument类是动态文档
class Mongodb_Books(mongoengine.Document):
"""
在Mongodb的表里ID是自动生成的所以这里不用写id,但是!这里创建的_id与自增Id不同,它是
ObjectID长度为12字节,由几个2 - 4字节的链组成。每个链代表并指定文档身份的具体内容。以下的值构成了完整的12字节组合:
一个 4 字节的值,表示自 Unix 纪元以来的秒数
一个 3 字节的机器标识符
一个 2 字节的进程 ID
一个 3 字节的计数器,以随机值开始
"""
# _id = mongoengine.ObjectIdField()
# 正常ID生成使用.SequenceField(),如果字段名不是_id在表中就会生成新的字段,并且不是主键,如果是_id就会在
# Mongodb ObjectID上自动把原有生成12字节的值,自动生成正常ID值。同时,会生成一个counters表,它是专门处
# 理id自增的表,它会结合Mongodb_Books来自动处理正常的ID值。
id = mongoengine.SequenceField(primary_key=True)
# numbers = mongoengine.IntField(auto_created=True, blank=True)
# 图书种类:如果用默认值就必须得用max_length
booksspecies = mongoengine.StringField(max_length=6, default='计算机')
# 图书名称,null=False:不允许为空值,unique=True:不允许重复
booksname = mongoengine.StringField(max_length=16, null=False, unique=True)
# 图书几本
booksnumber = mongoengine.IntField(null=False)
# 图书国籍:中国,美国,英国
bookscountry = mongoengine.StringField(max_length=4, null=False)
# 图书是否入库:默认值没有入库
booksstorage = mongoengine.IntField(max_length=1, null=False)
# 图书价格
booksmoney = mongoengine.StringField(max_length=10, null=False)
# 添加图书时间:auto_now_add:第一次创建的时候自动设置当前日期,默认值:false
bookstimes = mongoengine.DateTimeField(default=datetime.datetime.now)
# 图片名称
booksimg_name = mongoengine.StringField(null=False)
# 图片地址
booksimg = mongoengine.StringField(required=True)
class Meta:
db_table = 'Mongodb_Books'
urls.py 路由
urlpatterns = [
path('addmongodb', views.add_mongodb, name='add_mongodb'),
path('getmongodb/<int:id>/', views.get_mongodb, name='get_mongodb'),
path('updatemongodb/<int:id>/', views.update_mongodb, name='update_mongodb'),
path('delmongodb/<int:id>/', views.del_mongodb, name='del_mongodb'),
path('alldelmongodb', views.alldel_mongodb, name='alldel_mongodb'),
path('serchmongodb/<int:id>/', views.serch_mongodb, name='serch_mongodb'),
path('exportmongodbcsv/', views.export_mongodb_csv, name='export_mongodb_csv'),
path('exportmongodbxls/', views.export_mongodb_xls, name='export_mongodb_xls'),
]
views.py 视图
import csv
import os
import time
import xlwt
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from Mongodb.models import Mongodb_Books
#添加信息
def add_mongodb(request):
if request.method == "GET":
return render(request, 'booksadds.html')
elif request.method == "POST":
booksname = request.POST.get("booksname", None)
booksnumber = request.POST.get("booksnumber", None)
bookscountry = request.POST.get("bookscountry", None)
booksstorage = request.POST.get('booksstorage', None)
booksmoney = request.POST.get("booksmoney", None)
money = format(float(booksmoney), '.2f')
booksimg_name = request.POST.get("booksimg_name", None)
booksimg = request.FILES.get('booksimg', None)
try:
if booksimg_name == '' or booksimg == '':
return render(request, 'booksadds.html')
max_upload_size = 5242880
extenedname = booksimg_name[booksimg_name.rindex('.') + 1:]
allowedname = ['jpg', 'png', 'gif']
if extenedname not in allowedname or booksimg.size > max_upload_size:
return render(request, 'booksadds.html')
patha = os.path.join('static/uploads/' + time.strftime('%Y-%m-%d', time.localtime()))
if not os.path.exists(patha):
os.mkdir(patha)
pathb = os.path.join(patha + '/' + booksimg.name)
with open(pathb, 'wb') as f:
for i in booksimg.chunks():
f.write(i)
save = Mongodb_Books.objects.create(booksname=booksname, booksnumber=booksnumber, bookscountry=bookscountry,
booksstorage=booksstorage, booksmoney=money,
booksimg_name=booksimg_name, booksimg=pathb)
return redirect(reverse("mongodb:get_mongodb", kwargs={'id': 1}))
except Exception as ex:
return redirect(reverse("mongodb:add_mongodb"))
# 查询分页信息
def get_mongodb(request, id):
course_list = Mongodb_Books.objects.all().order_by("-id")
paginator = Paginator(course_list, 10)
page = request.GET.get("page", id)
currentPage = int(page)
try:
video_list = paginator.page(page)
except PageNotAnInteger:
video_list = paginator.page(1)
except EmptyPage:
video_list = paginator.page(paginator.num_pages)
return render(request, 'allbookss.html', locals())
#修改信息
def update_mongodb(request, id):
if request.method == "GET":
ob = Mongodb_Books.objects.get(pk=id)
context = {'data': ob}
return render(request, 'booksupdates.html', context)
elif request.method == "POST":
try:
obs = Mongodb_Books.objects.get(pk=id)
obs.booksname = request.POST['booksname']
obs.booksnumber = request.POST['booksnumber']
obs.bookscountry = request.POST['bookscountry']
obs.booksstorage = request.POST['booksstorage']
obs.booksmoney = format(float(request.POST['booksmoney']), '.2f')
obs.booksimg_name = request.POST['booksimg_name']
max_upload_size = 5242880
extenedname = obs.booksimg_name[obs.booksimg_name.rindex('.') + 1:]
allowedname = ['jpg', 'png', 'gif']
# 如果文件名不匹配,或者,获取表单文件的大小大于初始值max_upload_size:将进行返回所有数据重新上传文件
if extenedname not in allowedname or request.FILES.get("booksimg").size > max_upload_size:
context = {'data': obs}
return render(request, 'booksupdates.html', context)
# 再如果获取表单文件!= obs.booksimg原有数据,则进行删除原有目录和文件名,并且把新获取到的目录和文件名进行更新
elif request.FILES.get("booksimg") != obs.booksimg:
# 按照原有信息删除图片目录
path_booksimg = str(obs.booksimg)
os.remove(path_booksimg)
# 创建目录和上传文件
update_address = os.path.join(
'static/uploads/' + time.strftime('%Y-%m-%d', time.localtime()) + '/' + obs.booksimg_name)
# 把目录和地址传递给obs.booksimg
obs.booksimg = str(update_address)
# 创建一个变量进行获取静态页面带有File的文本框并且通过地址进行文件保存
aa = request.FILES.get("booksimg")
with open(update_address, 'wb') as f:
for chunk in aa.chunks():
f.write(chunk)
obs.save()
return redirect(reverse('mongodb:get_mongodb', kwargs={'id': 1}))
except Exception as ex:
ob = Mongodb_Books.objects.get(pk=id)
context = {'data': ob}
return render(request, 'booksupdates.html', context)
# 删除一条数据
def del_mongodb(request, id):
onedelete = Mongodb_Books.objects.get(pk=id)
book = onedelete.booksimg
path = str(book)
onedelete.delete()
os.remove(path)
return redirect(reverse("mongodb:get_mongodb", kwargs={'id': 1}))
# 删除多条数据
def alldel_mongodb(request):
if request.method == "GET":
return render(request, 'allbookss.html')
elif request.method == "POST":
ids = request.POST.getlist('id')
for i in ids:
deletesql = Mongodb_Books.objects.get(pk=i)
book = deletesql.booksimg
path = str(book)
deletesql.delete()
os.remove(path)
return redirect(reverse('mongodb:get_mongodb', kwargs={'id': 1}))
# 搜索信息
def serch_mongodb(request, id):
name = request.GET.get("booksname")
country = request.GET.get("bookscountry")
money = request.GET.get("booksmoney")
if not name != "" or money != "" or country != "":
ob_list = Mongodb_Books.objects.all().order_by("-id")
if name != "" or money != "" or country != "":
ob_list = Mongodb_Books.objects.filter(booksname=name).filter(bookscountry=country).filter(
booksmoney=money).order_by("-id")
if name != "":
ob_list = Mongodb_Books.objects.filter(booksname=name).order_by("-id")
if money != "":
ob_list = Mongodb_Books.objects.filter(booksmoney=money).order_by("-id")
if country != "":
ob_list = Mongodb_Books.objects.filter(bookscountry=country).order_by("-id")
paginator = Paginator(ob_list, 10)
page = request.GET.get("page", id)
currentPage = int(page)
try:
video_list = paginator.page(page)
except PageNotAnInteger:
video_list = paginator.page(1)
except EmptyPage:
video_list = paginator.page(paginator.num_pages)
return render(request, 'serchbookss.html', locals())
# 导出CSV格式文件
def export_mongodb_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="export_mongodb_csv.csv"'
writer = csv.writer(response)
writer.writerow(['ID编号', '图书种类', '图书名称', '入库几册', '图书国籍', '是否入库', '图书价格', '添加时间'])
export_csvdata = Mongodb_Books.objects.all().values_list('id', 'booksspecies', 'booksname', 'booksnumber',
'bookscountry', 'booksstorage', 'booksmoney',
'bookstimes').order_by("-id")
for i in export_csvdata:
writer.writerow(i)
return response
# 导出XLS格式文件
def export_mongodb_xls(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="export_mongodb_xls.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('bookinfo')
row_num = 0
columns = ['ID编号', '图书种类', '图书名称', '入库几册', '图书国籍', '是否入库', '图书价格', '添加时间', ]
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num])
export_xlsdata = Mongodb_Books.objects.all().values_list('id', 'booksspecies', 'booksname', 'booksnumber',
'bookscountry', 'booksstorage', 'booksmoney',
'bookstimes').order_by("-id")
for i in export_xlsdata:
row_num += 1
for col_num in range(len(i)):
ws.write(row_num, col_num, i[col_num])
wb.save(response)
return response
allbookss.html 查询分页静态页面
{% extends 'welcome.html' %}
{% load static %}
{% block header %}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>查看所有书信息</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" target="_blank" rel="external nofollow"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="{% static 'js/jquery-2.14.min.js' %}"></script>
<script src="{% static 'js/alldelete.js' %}"></script>
</head>
<body>
<form action="{% url 'mongodb:alldel_mongodb' %}" method="post">{% csrf_token %}
<div class="alert alert-warning" role="alert">
Allmongodbs/查看所有图书信息
</div>
<div class="panel panel-info">
<div class="panel-heading"><span class="glyphicon glyphicon-list" aria-hidden="true"></span> 查看所有图书信息
</div>
<div class="panel-body">
<div class="btn-group" role="group">
<button type="button" class="btn btn-info" οnclick="ALL_check()">全选</button>
<button type="button" class="btn btn-info" οnclick="ALL_uncheck()">反选</button>
<button type="submit" class="btn btn-warning">批量删除信息</button>
<button type="button" class="btn btn-success" οnclick="addinfo()">添加信息</button>
<button type="button" class="btn btn-info" οnclick="serchinfo()">搜索信息</button>
<button type="button" class="btn btn-success" οnclick="export_mongodb_CSV()">导出信息表CSV格式</button>
<button type="button" class="btn btn-success" οnclick="export_mongodb_XLS()">导出信息表XLS格式</button>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>管理信息</th>
<th>ID编号</th>
<th>图书种类</th>
<th>图书名称</th>
<th>入库几册</th>
<th>图书国籍</th>
<th>是否入库</th>
<th>图书价格</th>
<th>添加时间</th>
<th>文件路径</th>
</tr>
</thead>
<tbody>
{% for i in video_list %}
<tr>
<td id="testTbody">
<input type='checkbox' name="id" value="{{ i.id }}"/>
<a href="{% url 'mongodb:del_mongodb' i.id %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><span class="glyphicon glyphicon-trash"
aria-hidden="true"></span></a>
<a href="{% url 'mongodb:update_mongodb' i.id %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><span class="glyphicon glyphicon-pencil"
aria-hidden="true"></span></a>
</td>
<td>{{ i.id }}</td>
<td>{{ i.booksspecies }}</td>
<td>{{ i.booksname }}</td>
<td>{{ i.booksnumber }}</td>
<td>{{ i.bookscountry }}</td>
{% if i.booksstorage == 1 %}
<td>是</td>
{% else %}
<td>否</td>
{% endif %}
<td>¥{{ i.booksmoney }}</td>
<td>{{ i.bookstimes }}</td>
<td>{{ i.booksimg }}</td>
</tr>
{% empty %}
<tr>
<td colspan="12" align="center">
您还没有添加信息
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
{% if video_list.has_previous %}
<a class="disabled" href="{% url 'mongodb:get_mongodb' video_list.previous_page_number %}" target="_blank" rel="external nofollow"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% else %}
<a class="disabled" href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% endif %}
</li>
{% for num in paginator.page_range %}
{% if num == currentPage %}
<li class="active"><a class="page-link"
href="{% url 'mongodb:get_mongodb' num %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >{{ num }}</a></li>
{% else %}
<li><a class="page-link"
href="{% url 'mongodb:get_mongodb' num %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >{{ num }}</a></li>
{% endif %}
{% endfor %}
<li class="page-item">
{% if video_list.has_next %}
<a class="disabled" href="{% url 'mongodb:get_mongodb' video_list.next_page_number %}" target="_blank" rel="external nofollow"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% else %}
<a class="disabled" href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% endif %}
</li>
</ul>
</nav>
</form>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script language="JavaScript">
function addinfo() {
self.location = '{% url 'mongodb:add_mongodb' %}';
}
function serchinfo() {
window.location.href = '{% url 'mongodb:serch_mongodb' 1 %}';
}
function export_mongodb_CSV() {
window.location.href = '{% url 'mongodb:export_mongodb_csv' %}';
}
function export_mongodb_XLS() {
window.location.href = '{% url 'mongodb:export_mongodb_xls' %}';
}
</script>
</body>
</html>
{% endblock %}
add.html 添加静态页面
{% load static %}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static 'js/jquery-2.14.min.js' %}"></script>
</head>
<body>
<a href="{% url 'mongodb:get_mongodb' 1 %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >查看所有书信息</a>
<hr>
<form action="{% url 'mongodb:add_mongodb' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
图书名称:<input type="text" name="booksname" placeholder="请输入图书名称"><br>
入库几册:<input type="text" name="booksnumber" placeholder="请输入数字"><br>
图书国籍:<select name="bookscountry">
<option value="中国">中国</option>
<option value="美国">美国</option>
<option value="英国">英国</option>
</select><br>
是否入库:<input type="radio" name="booksstorage" value="1" checked="checked"/>是
<input type="radio" name="booksstorage" value="0"/>否<br>
图书价格:<input type="text" name="booksmoney" placeholder="请输入价格"><br>
<div class="form-group" style="margin-left: 30px">
<label for="fileupload">上传图片:</label>
<input type='text' class="form-control" name='booksimg_name' id='textfield' autocomplete="off"/>
<input id="fileupload" type="file" name="booksimg" style="display:none;"/>
<input id="excelImport" type="button" value="浏览" class="btn btn-primary"/>
</div>
<button>提交</button>
</form>
<script>
$(document).ready(function () {
$("#excelImport").click(function () {
$('#fileupload').click();
});
$("#uploadSubmit").click(function () {
$('#excelForm').submit();
});
$('#fileupload').change(function () {
document.getElementById("textfield").value =
document.getElementById("fileupload").files[0].name;
})
});
</script>
</body>
</html>
serch.html 搜索静态页面
{% load static %}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>查看所有书信息</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" target="_blank" rel="external nofollow"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="{% static 'js/jquery-2.14.min.js' %}"></script>
<script src="{% static 'js/alldelete.js' %}"></script>
</head>
<body>
<form action="{% url 'mongodb:serch_mongodb' 1 %}" method="get">{% csrf_token %}
图书名称:<input type="text" name="booksname" placeholder="请输入图书名称">
图书国籍:
<select name="bookscountry">
<option value="">请选择国家</option>
<option value="中国">中国</option>
<option value="美国">美国</option>
<option value="英国">英国</option>
</select>
图书价格:<input type="text" name="booksmoney" placeholder="请输入价格">
<button>搜索</button>
</form>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{% url 'mongodb:add_mongodb' %}" target="_blank" rel="external nofollow" ><span
class="label label-success">添加信息</span></a></li>
<li class="breadcrumb-item"><a href="{% url 'mongodb:get_mongodb' 1 %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" ><span
class="label label-success">查看所有信息</span></a></li>
</ol>
</nav>
<form action="{% url 'mongodb:alldel_mongodb' %}" method="post">{% csrf_token %}
<div class="alert alert-warning" role="alert">
Allbooks/查看所有书
</div>
<button type="button" class="btn btn-outline-info" οnclick="ALL_check()">全选</button>
<button type="button" class="btn btn-outline-info" οnclick="ALL_uncheck()">反选</button>
<button type="submit" class="btn btn-outline-warning">删除</button>
<br>
<table class="table table-bordered">
<thead>
<tr>
<th>管理信息</th>
<th>ID编号</th>
<th>图书种类</th>
<th>图书名称</th>
<th>入库几册</th>
<th>图书国籍</th>
<th>是否入库</th>
<th>图书价格</th>
<th>添加时间</th>
<th>文件路径</th>
</tr>
</thead>
<tbody>
{% for i in video_list %}
<tr>
<td id="testTbody">
<input type='checkbox' name="id" value="{{ i.id }}"/>
<a href="{% url 'mongodb:del_mongodb' i.id %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >删除</a> |<a href="{% url 'mongodb:update_mongodb' i.id %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >修改</a>
</td>
<td>{{ i.id }}</td>
<td>{{ i.booksspecies }}</td>
<td>{{ i.booksname }}</td>
<td>{{ i.booksnumber }}</td>
<td>{{ i.bookscountry }}</td>
{% if i.booksstorage == True %}
<td>是</td>
{% else %}
<td>否</td>
{% endif %}
<td>¥{{ i.booksmoney }}</td>
<td>{{ i.bookstimes }}</td>
<td>{{ i.booksimg }}</td>
</tr>
{% empty %}
<tr>
<td colspan="12" align="center">
您没有搜索到相关信息
</td>
</tr>
{% endfor %}
</tbody>
</table>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item">
{% if video_list.has_previous %}
<a class="page-link" href="{% url 'mongodb:serch_mongodb' video_list.previous_page_number %}" target="_blank" rel="external nofollow"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% else %}
<a class="page-link" href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
{% endif %}
</li>
{% for num in paginator.page_range %}
{% if num == currentPage %}
<li class="page-item"><a class="page-link"
href="{% url 'mongodb:serch_mongodb' num %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >{{ num }}</a></li>
{% else %}
<li class="page-item"><a class="page-link"
href="{% url 'mongodb:serch_mongodb' num %}" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >{{ num }}</a></li>
{% endif %}
{% endfor %}
<li class="page-item">
{% if video_list.has_next %}
<a class="page-link" href="{% url 'mongodb:serch_mongodb' video_list.next_page_number %}" target="_blank" rel="external nofollow"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% else %}
<a class="page-link" href="#" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
{% endif %}
</li>
</ul>
</nav>
</form>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"
integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
</body>
</html>