sweetalert弹窗

  • 下载sweetalert并存放在Django项目中的静态文件夹中 https://github.com/MrBigBlake/bootstrap-sweetalert
  • 选择想要的弹窗样式直接copy过来快乐的改呀改https://lipis.github.io/bootstrap-sweetalert/
  • 如何查找到for循环中的a标签: 可以添加一个类属性
  • 通过DOM操作直接移除页面上已经被删除的数据标签
# 通过sweetalert实现删除数据时触发弹窗, 确认是否删除
def home(request):
user_queryset = models.User.objects.all()
if request.is_ajax():
back_dic = {'code': 1000, 'msg': ''}
print(request.POST)
delete_id = int(request.POST.get('delete_id')[0])
time.sleep(2)
models.User.objects.filter(pk=delete_id).delete()
back_dic['msg'] = 'Data has been deleted'
return JsonResponse(back_dic)
return render(request, 'home.html', locals())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'JQuery-3.4.1/JQuery.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap-sweetalert-master/dist/sweetalert.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-sweetalert-master/dist/sweetalert.css' %}">
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<div class="row"></div>
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">User Info</h1>
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>NO.</th>
<th>Username</th>
<th>Age</th>
<th>Gender</th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
{% for user in user_queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.username }} </td>
<td>{{ user.age }} </td>
<td>{{ user.get_gender_display }} </td>
<td class="text-center">
<a href="#" class="btn btn-primary btn-sm">Edit</a>
{#给a标签加一个cancel类以便定位到该标签#}
<a href="#" class="btn btn-danger btn-sm cancel" id={{ user.pk }}>Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div> <script>
$(".cancel").click(function () {
let $btn = $(this);
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false,
showLoaderOnConfirm: true
},
function (isConfirm) {
if (isConfirm) {
$.ajax({
url: "",
type: "post",
data: {"delete_id": $btn.attr('id')},
success: function (data) {
if (data.code==1000) {
swal("Deleted!", "Data has been deleted.", "success");
{#通过DOM操作直接将删除的标签移除#}
$btn.parent().parent().remove()
} else {
swal("Error", "Unknown error", "warning");
}
}
});
} else {
swal("Cancelled", "Data delete has been cancelled :)", "error");
}
})
});
</script>
</body>
</html>

bulk-create

  • 用于向数据库中批量添加数据
  • 先将数据对象都添加到列表中, 然后将该列表传给bulk_create方法
# 这样向数据库添加大量数据速度非常慢, 甚至会导致程序崩溃
for i in range(10000):
models.Book.objects.create(title=f'book-{i}') # 使用bulk_create方法可快速向数据库中添加大量数据对象
lis = []
for i in range(10000):
obj = models.Book(title=f'book-{i}')
lis.append(obj)
models.Book.objects.bulk_create(lis)

自定义分页器

  • queryset对象支持切片操作
  • 可以直接向html文件发送html代码(字符串格式)
# 实现简单的分页展示效果
def index(request):
# 分页器一次展示的页数为 page_controller * 2 + 1
page_controller = 3
if page_controller < 1:
page_controller = 1 # 数据库图书个数
book_num = models.Book.objects.all().count()
per_page_num = 5 # 判断一共有多少页
page_num, more = divmod(book_num, per_page_num)
if more:
page_num += 1 # 获取当前页数, 设置默认值为1
page_init = int(request.GET.get('page', 1))
page = page_init # 防止分页器末尾超出总页数
if page_init > page_num - page_controller:
page = page_num - page_controller # 防止分页器开头出现0或负数页
if page_init < page_controller + 1:
page = page_controller + 1 # 切片操作的起始和结束位置
page_start = (page_init - 1) * per_page_num
page_end = page_init * per_page_num # 切片获取当前页数对应的图书数据
book_queryset = models.Book.objects.all()[page_start: page_end] # 直接向html文件发送html代码
html = ''
for i in range(page - page_controller, page + page_controller + 1): # 当前页标签高亮
if i == page_init:
html += f'<li class="active"><a href="?page={i}">{i}</a></li>'
else:
html += f'<li><a href="?page={i}">{i}</a></li>' return render(request, 'index.html', locals())
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'JQuery-3.4.1/JQuery.js' %}"></script>
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Book List</h1>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>NO.</th>
<th>Book Title</th>
</tr>
</thead>
<tbody>
{% for book in book_queryset %}
<tr>
<td>{{ book.pk }}</td>
<td>{{ book.title }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center">
<nav aria-label="Page navigation">
<ul class="pagination">
{{ html|safe }}
</ul>
</nav>
</div>
</div>
</div>
</div>
</body>
</html>
  • 第三方分页器的使用
  • 在app文件夹或者总项目文件夹下, 新建utils文件夹, 将下面分页文件放到utils文件下
  • 两个参数: current_pageall_count
  • 将html代码字符串封装到了 pagination_obj.page_html
# Pagination.py
class Pagination(object):
def __init__(self,current_page,all_count,per_page_num=10,pager_count=5):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数 用法:
queryset = model.objects.all()
page_obj = Pagination(current_page,all_count)
page_data = queryset[page_obj.start:page_obj.end]
获取数据用page_data而不再使用原始的queryset
获取前端分页样式用page_obj.page_html
"""
try:
current_page = int(current_page)
except Exception as e:
current_page = 1 if current_page <1:
current_page = 1 self.current_page = current_page self.all_count = all_count
self.per_page_num = per_page_num # 总页码
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager self.pager_count = pager_count
self.pager_count_half = int((pager_count - 1) / 2) @property
def start(self):
return (self.current_page - 1) * self.per_page_num @property
def end(self):
return self.current_page * self.per_page_num def page_html(self):
# 如果总页码 < 11个:
if self.all_pager <= self.pager_count:
pager_start = 1
pager_end = self.all_pager + 1
# 总页码 > 11
else:
# 当前页如果<=页面上最多显示11/2个页码
if self.current_page <= self.pager_count_half:
pager_start = 1
pager_end = self.pager_count + 1 # 当前页大于5
else:
# 页码翻到最后
if (self.current_page + self.pager_count_half) > self.all_pager:
pager_end = self.all_pager + 1
pager_start = self.all_pager - self.pager_count + 1
else:
pager_start = self.current_page - self.pager_count_half
pager_end = self.current_page + self.pager_count_half + 1 page_html_list = []
# 添加前面的nav和ul标签
page_html_list.append('''
<nav aria-label='Page navigation>'
<ul class='pagination'>
''')
first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
page_html_list.append(first_page) if self.current_page <= 1:
prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
else:
prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,) page_html_list.append(prev_page) for i in range(pager_start, pager_end):
if i == self.current_page:
temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
else:
temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
page_html_list.append(temp) if self.current_page >= self.all_pager:
next_page = '<li class="disabled"><a href="#">下一页</a></li>'
else:
next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
page_html_list.append(next_page) last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
page_html_list.append(last_page)
# 尾部添加标签
page_html_list.append('''
</nav>
</ul>
''')
return ''.join(page_html_list)
def index(request):
book_queryset = models.Book.objects.all()
# 两个参数, 当前页和数据数量
current_page = request.GET.get('page', 1)
all_count = book_queryset.count()
# 实例化出分页器对象
pagination_obj = Pagination(current_page=current_page, all_count=all_count)
# 切片获取当前页的数据
page_queryset = book_queryset[pagination_obj.start:pagination_obj.end]
return render(request, 'index.html', locals())
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>NO.</th>
<th>Book Title</th>
</tr>
</thead>
<tbody>
{% for book in page_queryset %}
<tr>
<td>{{ book.pk }}</td>
<td>{{ book.title }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="text-center">
{{ pagination_obj.page_html|safe }}
</div>
</div>

Django 08的更多相关文章

  1. Django 08 Django模型基础3(关系表的数据操作、表关联对象的访问、多表查询、聚合、分组、F、Q查询)

    Django 08 Django模型基础3(关系表的数据操作.表关联对象的访问.多表查询.聚合.分组.F.Q查询) 一.关系表的数据操作 #为了能方便学习,我们进入项目的idle中去执行我们的操作,通 ...

  2. django之ajax结合sweetalert使用,分页器和bulk_create批量插入 07

    目录 sweetalert插件 bulk_create 批量插入数据 分页器 简易版本的分页器的推导 自定义分页器的使用(组件) sweetalert插件 有这么一个需求: ​ 当用户进行一个删除数据 ...

  3. Django框架08 /聚合查询、分组、F/Q查询、原生sql相关

    Django框架08 /聚合查询.分组.F/Q查询.原生sql相关 目录 Django框架08 /聚合查询.分组.F/Q查询.原生sql相关 1. 聚合查询 2. 分组 3. F查询和Q查询 4. o ...

  4. 08 Django REST Framework 解决前后端分离项目中的跨域问题

    01-安装模块 pip install django-cors-headers 02-添加到INSTALL_APPS中 INSTALLED_APPS = ( ... 'corsheaders', .. ...

  5. Django REST Framework API Guide 08

    1.Filtering 2.Pagination FIltering GenericAPIView的子类筛选queryset的简单方法是重写.get_quueryset()方法. 1.根据当前用户进行 ...

  6. 08: Django使用haystack借助Whoosh实现全文搜索功能

    参考文章01:http://python.jobbole.com/86123/ 参考文章02: https://segmentfault.com/a/1190000010866019 参考官网自定制v ...

  7. 2018.08.30 21:12 第一个Django程序完成

    from django.http import HttpResponse def hello(request): return HttpResponse("Hello world ! &qu ...

  8. python学习笔记08:安装django

    linux环境安装django: sudo pip install django windows环境安装django: pip install django 验证django是否安装: python ...

  9. Django 2.0 学习(08):Django 自动化测试

    编写我们的第一个测试 确定bug 幸运的是,在polls应用中存在一个小小的bug急需修复:无论Question的发布日期是最近(最后)的日期,还是将来很多天的日期,Question.was_publ ...

随机推荐

  1. nyoj 48-小明的调查作业(set)

    48-小明的调查作业 内存限制:64MB 时间限制:1000ms Special Judge: No accepted:15 submit:29 题目描述: 小明的老师布置了一份调查作业,小明想在学校 ...

  2. setState何时同步,何时异步,为什么?

    setState何时同步,何时异步,为什么 答案:在React库控制时,异步:否则同步. 示例代码如下: constructor(props){ super(porps); this.state = ...

  3. 理解Spark SQL(二)—— SQLContext和HiveContext

    使用Spark SQL,除了使用之前介绍的方法,实际上还可以使用SQLContext或者HiveContext通过编程的方式实现.前者支持SQL语法解析器(SQL-92语法),后者支持SQL语法解析器 ...

  4. Centos上通过shell脚本备份数据库

    #!/bin/bash ds=`` list=`date +%Y`/`date +%m` dname="callme" eval "mkdir -p $list" ...

  5. 【MongoDB】2019年MongoDB中文社区广州大会,干货满满的分享活动

    1 介绍 MongoDB中文社区(mongoing.com)是大中华区获得官方认可的中文社区,11月23日下午,在广州举办了线下用户大会,带给大家一手干货和实践. 2 大会议程 大会组织者对时间的把控 ...

  6. Python第五天 列表练习 元组类型 字典类型 小购物车练习

    # 反转 reverse# l=['lili','asdf','qwer','80000']# l.reverse()# print(l) # ['80000', 'qwer', 'asdf', 'l ...

  7. [ubuntu篇] 使用Hexo建立个人博客,自定义域名https加密,搜索引擎google,baidu,360收录

    为了更好的阅读体验,欢迎阅读原文.原文链接在此. Part 1: Using Github Pages and Hexo to manage personal blogs. Series Part 1 ...

  8. convert svn repo to git

    https://john.albin.net/git/convert-subversion-to-git 1. 抓取Log 在linux 上做的,其余是在win上做的. 2. svn co svn:/ ...

  9. php如何处理大数据高并发

    大数据解决方案 使用缓存: 使用方式:1,使用程序直接保存到内存中.主要使用Map,尤其ConcurrentHashMap. 使用缓存框架.常用的框架:Ehcache,Memcache,Redis等. ...

  10. .NET Core 3.0 使用Nswag生成Api文档和客户端代码

    摘要 在前后端分离.Restful API盛行的年代,完美的接口文档,成了交流的纽带.在项目中引入Swagger (也称为OpenAPI),是种不错的选择,它可以让接口数据可视化.下文将会演示 利用N ...