day58
ajax结合sweetalert使用
首先下载sweetalert 下载到本地文件
然后导入
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/font-awesome-4.7.0/css/font-awesome.min.css' %}">
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/bootstrap-sweetalert-master/dist/sweetalert.css' %}">
然后在script中写入:
{% block js %}
<script>
$('.remove').click(function(){
var $btn=$(this); #生成标签对象
swal({
title: "确定删除吗?",
text: "会永久删除!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "删除!",
cancelButtonText: "不删除!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {#这边判断回调函数传过来的值,它会自动自动解析json数据
$.ajax({
url:"{% url 'app01_delete_book' %}",
type:'post',
data:{'delete_id':$btn.attr('bookid')},#通过标签对象里的属性取值
success:function(data){
if(data.code==1000) {
swal("删除成功!", data.msg , "success");
$btn.parent().parent().remove()#寻找标签对象上一级进行删除
}else{
swal('发生错误','未知错误!','warning')
}
}
})
} else {
swal("取消", "文件保存良好 :)", "error");
}
});
})
</script>
{% endblock %}
bulk_create批量插入数据
具体操作就是先定义一个列表,然后许多生成对象,再把对象全部传入列表,在通过bulk_create插入数据库数据
book_list = []
for i in range(100):
book_list.append(models.Book(title='第%s书'%i))
# 批量插入数据 建议使用bulk_create方法
models.Book.objects.bulk_create(book_list)
简易版本的分页器推导
一页展示的条数
per_page_num = 10
all_count = book_queryset.count()#所有的数据
all_page_num,more = divmod(all_count,per_page_num)
if more:
all_page_num += 1 # 到底需要多少页面展示
# 用户想要查看的页码
current_page = request.GET.get('page', 1)#若没有传来值,给他一个默认值
current_page = int(current_page)
start_page = (current_page - 1) * per_page_num
end_page = current_page * per_page_num
html = ''
xxx = current_page
if current_page < 6:
xxx = 6
for i in range(xxx-5,xxx+6):
if current_page == i:
html += '<li class="active"><a href="?page=%s">%s</a></li>'%(i,i)
else:
html += '<li><a href="?page=%s">%s</a></li>' % (i, i)
book_queryset = book_queryset[start_page:end_page]
return render(request, 'index.html', {'xxx':book_queryset}# 第一种)
local()#第二种 可以传入所有
自定义分页器的使用
自己创建一个utils文件夹,然后在文件夹下创建mypage文件,在里面写入Pagination对象
使用方法:
current_page = request.GET.get('page',1)
all_count = book_queryset.count()
page_obj = Pagination(current_page=current_page,all_count=all_count,per_page_num=10,pager_count=5)
page_queryset = book_queryset[page_obj.start:page_obj.end] # book_queryset = book_queryset[start_page:end_page]
return render(request,'index.html',locals())