12.2 总结

扫码查看

1.ajax结合sweetalert实现删除按钮动态效果

#views.py
import time
def home(request):
    if request.is_ajax():
        back_dic={'code':1000,'msg':''}
        delete_id=request.POST.get('delete_id')
        time.sleep(3)
        models.User.objects.filter(pk=delete_id).delete()
        back_dic['msg']='数据已经被我删了'
        return JsonResponse(back_dic)
    user_quertset=models.User.objects.all()
    return render(request,'home.html',locals())

#home.html
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'dist/sweetalert.min.js' %}"></script>
    <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    <style>
        div.sweet-alert h2 {
            padding: 10px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-center">数据展示</h2>
            <br>
            <table class="table table-hover table-striped table-bordered">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>用户名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th class="text-center">操作</th>
                </tr>
                </thead>

                <tbody>
                {% for userobj in user_quertset %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ userobj.username }}</td>
                        <td>{{ userobj.age }}</td>
                        <td>{{ userobj.get_gender_display }}</td>
                        <td class="text-center">
                            <a href="#" class="btn btn-primary btn-sm">编辑</a>
                            <a href="#" class="btn btn-danger btn-sm cancel" userId={{ userobj.pk }}>删除</a>
                        </td>
                    </tr>
                {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    $('.cancel').click(function () {

        var $btn = $(this)
        swal({
                title: "你确定要删除吗?",
                text: "你如果删了,后果不堪设想!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "是的,我就要删!",
                cancelButtonText: "那就算了吧!",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            },
            function (isConfirm) {
                if (isConfirm) {
                    //朝后端发送ajex请求
                    $.ajax({
                        url: '',
                        type: 'post',
                        data: {'delete_id': $btn.attr('userId')},
                        success: function (data) {
                            if (data.code == 1000) {
                                swal("准备跑路吧!", data.msg, 'success');

                                //通过DOM操作 来直接操作标签
                                $btn.parent().parent().remove()
                            } else {
                                swal('有bug', '发生了未知错误!', 'warning');
                            }
                        }
                    });
                } else {
                    swal("呵呵", "数据都不敢删", "error");
                }
            });
    })

</script>
</body>

2.bulk_create批量插入数据

for i in range(1000):
    models.book.object.create(title='第%本书'%i)
    #这样做运行很慢,花了六百多毫秒

#批量插入数据,建议使用bulk_create方法

book_list = []
    for i in range(100):
        book_list.append(models.Book(title='第%s书'%i))
        #不走数据库 首先生成10000个对象
models.Book.objects.bulk_create(book_list)

3.自定义分页器思路:

分页意味着对总的数据做切片操作,每一次展示一块内容。恰巧queryset支持切片操作(不支持负数),用get请求实现翻页的跳转功能。

#views.py
# 一页展示的条数
    per_page_num = 10
    book_queryset = models.Book.objects.all()
#总共有多少条数据
    all_count = book_queryset.count()
    #结果是元组,解压赋值
    all_page_num,more = divmod(all_count,per_page_num)  #熟知divmod的用法
    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

    book_queryset = book_queryset[start_page:end_page]
    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)

     return render(request,'index.html',locals())
#index.html(分页器)
<nav aria-label="Page navigation">
  <ul class="pagination">
    <li>
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
    <li><a href="?page=1">1</a></li>
    <li><a href="?page=2">2</a></li>
    <li><a href="?page=3">3</a></li>
    <li><a href="?page=4">4</a></li>
    <li><a href="?page=5">5</a></li>
    <li>
      <a href="#" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>

4.分页器组件

#views.py
from app01.utils.mypage import Pagination
def index(request):
    book_queryset=models.Book.objects.all()

    #自定义分页器的使用
    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())

#index.html不使用分页器普通组件,使用动态组件
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% for book in page_queryset %}
            <!--将页面上原本的queryset数据全部换成切片之后的queryset即可-->
                <p>{{ book }}</p>
            {% endfor %}
            {{ page_obj.page_html|safe }}
        </div>
    </div>
</div>
12-22 18:20
查看更多