django与ajax:ajax结合sweetalter ,批量插入数据 ;分页器组件

一、ajax结合sweetalter

  • """
    如果是ajax进行前后端交互,通常后端会返回给ajax一个字典
    """
    
  • ajax结合sweetalter实现点击删除按钮时,弹出提示框,提现用户是否真的要删除,点击”确定“删除,点击”取消“返回。并且在不刷新页面的情况下,不显示被删除的那一行。

  • 首先sweetalter是第三方组件,要先下载导入或者使用cdn的

  • 实例

  • 前端步骤:实例代码中的注释对应下面的4个步骤

    1. 展示完信息后,删除按钮中添加自定义属性来获取当前这条数据的主键值——》

    2. 给删除按钮绑定点击事件,事件函数内部书写模态框代码(模态框代码模板直接从Bootstrap的组件中拷贝,再根据需求修改)——》

    3. 在模态框代码的确定按钮中加入ajax请求。——》

    4. 用户点击模态框中的确定时,执行DOM操作,将我们要删除的那个tr标签移除即可。

# 前端:

<!DOCTYPE html>
<html lang="en">
<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 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.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-bordered table-striped">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>用户名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th class="text-center">操作</th>
                </tr>
                </thead>
                <tbody>
                {% for userObj in user_queryset %}
                    <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>
                            
                    	<!--******************** 1.添加自定义属性获取主键值 ***************-->
                            
                            <a href="#" class="btn btn-danger btn-sm cancel" userId = {{ userObj.pk }}>删除</a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>


<script>
	<!--******************** 1.绑定点击事件 ***************-->
    $('.cancel').click(function () {
        var $btn = $(this);
        <!--******************** 模态框 ***************-->
        swal({
                title: "你确定要删吗?",
                text: "你如果删了,你就准备好直接跑路吧!",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "是的,老子就要删!",
                cancelButtonText: "算了算了,不敢!",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            },
            <!--************* 3.在模态框代码的确定按钮中加入ajax请求 ***************-->
            function (isConfirm) {
                if (isConfirm) {
                    // 朝后端发送ajax请求
                    $.ajax({
                        url:'',
                        type:'post',
                        data:{'delete_id':$btn.attr('userId')},
                        success:function (back_data) {
                            if(back_data.code==1000){

                                swal("准备跑路把!", back_data.msg, "success");
                                
                                <!--********* 4.执行DOM操作,将对应的tr标签移除 ***********-->
                                $btn.parent().parent().remove()
                            }else{
                                swal("有Bug", "发什么了未知的错误!", "warning");
                            }
                        }
                    });
                } else {
                    swal("怂逼", "数据都不敢删", "error");
                }
            });
    })
</script>
</body>
</html>



# 后端:

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()
        return JsonResponse(back_dic)  # 后端返回到前端的json格式数据,前端会自动反序列化成JS对象,因此在上面的ajax回调函数中可以直接使用back_data.code 和 back_data.msg
    user_queryset = models.User.objects.all()
    return render(request,'home.html',locals())

二、bulk_create批量插入数据

  • django的orm中,当直接批量插入大量数据时,效率非常低,并且会中途中断。

  • 这是django就有一个方法bulk_create,来帮我们实现批量插入数据,这个方法不仅可以成功插入大量数据,且效率也很高。

  • 实例

def index(request):
    # for i in range(1000):
    #     models.Book.objects.create(title='第%s本书'%i)  # 直接插入,效率低,中间会中断
    book_list = []
    for i in range(100):
        book_list.append(models.Book(title='第%s书'%i))
    # 批量插入数据 建议使用bulk_create方法
    models.Book.objects.bulk_create(book_list)

三、简易版分页器推导

1. 推导步骤

  1. 首先获取全部要展示的数据对象,统计总数

    all_count = book_queryset.count()
    
  2. 事先决定每页展示多少条数据,再计算总共分了多少页(使用python自带的取整取余内置方法divmod()

    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)
    
    
    
  3. 决定每个页面上展示多少个页码给用户,并是用户每次点击的页码高亮显示且处于这些展示出来的页码的中间。(此时要对最前面的几页和最后面的几页做一个判断,这里我们就只演示对最前面的几页做判断)

    # 决定每个页面上展示多少个页码给用户,用户每次点击的页码处于这些展示出来的页码的中间
    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)
    
  4. 确定每页展示哪些数据

    book_queryset = book_queryset[start_page:end_page]  # 顾头不顾尾(支持索引取值和索引切片)
    return render(request, 'index.html', {'xxx':book_queryset})
    

四、自定义分页器的使用

1. 自定义分页器模板

class Pagination(object):
    def __init__(self,current_page,all_count,per_page_num=2,pager_count=11):
        """
        封装分页相关数据
        :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)

2. 使用方法

  1. 在app文件夹下新建一个utils文件夹,在utils文件夹下新建一个任意名字的py文件(如:mypage.py)
  2. 将上面的自定义分页器模板代码拷贝到该py文件中
  3. 在需要分页的功能函数中导入from app01.utils.mypage import Pagination

(1)后端代码和前端代码

  • 注意:在前端代码中,将所有的book_queryset对象换成page_queryset对象
# 后端代码:
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对象赋值给page_queryset

return render(request,'index.html',locals())  


# 前端代码:


<!DOCTYPE html>
<html lang="en">
<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 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.min.js' %}"></script>
</head>
<body>
<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>

</body>
</html>
原文地址:https://www.cnblogs.com/Mcoming/p/11971990.html