sweetalert和分页器的使用
<!--book_list.html-->
{% extends 'home.html' %}
{% block content %}
<div>
<p><a href="{% url 'add' %}" class="btn btn-success">新增</a></p>
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>id</th>
<th>book name</th>
<th>author</th>
<th>price</th>
<th>publish</th>
<th>actions</th>
</tr>
</thead>
<tbody>
<!--注意循环取出分页器划分好的一页的数据-->
{% for book in page_queryset %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>
{% for author in book.author.all %}
{% if forloop.last %}
{{ author }}
{% else %}
{{ author }},
{% endif %}
{% endfor %}
</td>
<td>{{ book.price }}</td>
<td>{{ book.publish.name }}</td>
<td>
<a href="#" class="btn btn-primary btn-sm">编辑</a>
<a href="#" class="btn btn-primary btn-sm cancel" userId="{{ book.pk }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<!--分页器-->
<div class="text-center">
{{ page_obj.page_html|safe }}
</div>
</div>
{% endblock %}
{% block js %}
<!--sweetalert-->
<script>
$('.cancel').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) {
$.ajax({
url:'',
type:'post',
data:{'delete_id':$btn.attr('userId')},
success:function(data) {
if (data.code==1000) {
swal("删除成功!", data.msg, "success");
// 前端删除
$btn.parent().parent().remove()
} else {
swal("有bug", "未知错误!", "warning")
$btn.parent().parent().remove()
}
}
})
} else {
swal("取消成功", "Your imaginary file is safe :)", "error");
}
});
})
</script>
{% endblock %}
# views.py
def book_list(request):
if request.is_ajax():
back_dic = {'code': 1000, 'msg': ''}
delete_id = request.POST.get('delete_id')
models.Book.objects.filter(pk=delete_id).delete()
back_dic['msg'] = '数据已删除!'
return JsonResponse(back_dic)
# 分页器的使用
current_page = request.GET.get('page', 1)
all_count = book_list.count()
page_obj = Pagination(current_page=current_page, all_count=all_count, per_page_num=5, pager_count=5)
page_queryset = book_list[page_obj.start:page_obj.end] # book_queryset = book_queryset[start_page:end_page]
return render(request, 'book_list.html', locals())