自制paginator.py

作者: 天才一般的幼稚 | 来源:发表于2019-02-26 19:52 被阅读0次

最近在做Django时自己写了一个Paginator来配合Ajax动态获取数据。
1、paginator.py

# coding=utf-8
import json
import datetime
from django.forms.models import model_to_dict

class Paginator:
    # obj_list:传入的对象列表; count:每一页记录的条数
    def __init__(self, obj_list, count, index):
        self.obj_list = obj_list
        self.count = count
        self.index = index

    # 计算总页数
    def page_num(self):
        length = len(self.obj_list)
        if length % self.count != 0:
            return length // self.count + 1
        else:
            return length / self.count

    # 计算当前索引页记录条数
    def page_index_num(self):
        pre_obj_count = self.count * (self.index - 1)
        if pre_obj_count + self.count > len(self.obj_list):
            return len(self.obj_list) - pre_obj_count
        else:
            return self.count

    # 返回当前页记录的json集合
    def page(self):
        json_list = []
        day = datetime.datetime.now()
        page_index_num = self.page_index_num()
        # 循环当前页
        for i in range(self.count*(self.index-1), self.count*(self.index-1)+page_index_num):
            attr_dic = self.obj_list[i].__dict__    # 取得记录对象的所有属性
            del attr_dic['_state']  # 删除不需要的属性
            if '_puser_cache' in attr_dic:  # 外键json化
                attr_dic['_puser_cache'] = model_to_dict(attr_dic['_puser_cache'])
                # datetime类型无法直接转化,这里没有用到此属性,故删除,如有需要参照下面的方法json化
                del attr_dic['_puser_cache']['ulogintime']  
            for key in attr_dic:
                if type(attr_dic[key]) == type(day):
                    json_time = {'year': attr_dic[key].year, 'month': attr_dic[key].month, 'day': attr_dic[key].day,
                                 'hour': attr_dic[key].hour, 'minute': attr_dic[key].minute}
                    attr_dic[key] = json_time
            json_list.append(attr_dic)
        # print(json_list)
        return json_list

views.py

@csrf_exempt
def manage(request, uid, pindex):
    if request.session.get('user_id') is None:
        return render(request, 'user/login.html')
    else:
        if pindex == '':
            pindex = '1'
        from_time = ""
        to_time = ""
        picture_list = PictureInfo.objects.filter(puser_id=uid, pstatus='1')
       
        # 处理取得的时间,若from_time为空,则用1970-01-01,若to_time为空,则用当前时间
        def time_splits(times, num):
            if times is not None and times != 'None':
                datetimee = times.split('T')
                date = datetimee[0].split('-')
                timee = datetimee[1].split(':')
                year = int(date[0])
                month = int(date[1])
                day = int(date[2])
                hour = int(timee[0])
                minute = int(timee[1])
                timestamp = time.mktime(datetime.datetime(year, month, day, hour, minute, 0).timetuple())
                return timestamp
            elif num == 2:
                year = time.strftime('%Y', time.localtime(time.time()))
                month = time.strftime('%m', time.localtime(time.time()))
                day = time.strftime('%d', time.localtime(time.time()))
                hour = time.strftime('%H', time.localtime(time.time()))
                minute = time.strftime('%M', time.localtime(time.time()))
                timestamp = time.mktime(datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), 0).timetuple())
                return timestamp
            else:
                timestamp = time.mktime(datetime.datetime(1970, 1, 1, 0, 0, 0).timetuple())
                return timestamp
        if request.method == "POST":
            # 搜索
            if request.POST.get('from') != "" or request.POST.get('to') != "":
                from_time = request.POST.get('from')
                to_time = request.POST.get('to')

                from_time_timestamp = time_splits(from_time, 1)
                to_time_timestamp = time_splits(to_time, 2)

                picture = PictureInfo.objects.filter(puser_id=uid, pstatus='1')
                print(type(picture[0].pcreatetime))
                picture_list = []
                for pic in picture:
                    timestamp = time.mktime(
                        datetime.datetime(pic.pcreatetime.year, pic.pcreatetime.month, pic.pcreatetime.day,
                                          pic.pcreatetime.hour, pic.pcreatetime.minute, 0).timetuple())
                    if from_time_timestamp <= timestamp <= to_time_timestamp:
                        picture_list.append(pic)

            paginator = Paginator(picture_list, 10, int(pindex))
            page_num = paginator.page_num()
            page_index_num = paginator.page_index_num()
            page_json_list = paginator.page()

            context = {'page_num': page_num, 'page_index_num': page_index_num, 'page': page_json_list, 'pindex': pindex, 'from_time': from_time,
                       'to_time': to_time}
            return JsonResponse(json.dumps(context), safe=False)
        return render(request, 'home/manage.html', {'title': 'Management', 'color':'2'})

manage.html

{% extends 'user_base.html' %}
{% load home_tags %}
{% block title %}
{{ title }}
{% endblock title %}
{% block context %}
<!-- main-heading -->
            <h2 class="main-title-w3layouts mb-2 text-center">Management</h2>
                <div class="outer-w3-agile col-xl ml-xl-3 mt-xl-0 mt-3">
                    <!-- Search-from -->
                    <form action="/home/manage/uid={{ request.session.user_id }}/page={{ pindex }}" method="POST" class="form-inline mx-auto search-form">
                        From &nbsp;<input class="form-control mr-sm-2" type="datetime-local" name="from" id="from" value="">
                        To &nbsp;<input class="form-control mr-sm-2" type="datetime-local" name="to" id="to" value="">&nbsp;
                        <button class="btn btn-style my-2 my-sm-0" type="button" id="search">Search</button>
                    </form>
                    <!--// Search-from -->
                    <hr/>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th class="text-center">
                                    S/N
                                </th>
                                <th class="text-center">
                                    create time
                                </th>
                                <th class="text-center">
                                    image
                                </th>
                                <th class="text-center">
                                    predicted time
                                </th>
                                <th class="text-center">
                                    for more details
                                </th>
                            </tr>
                        </thead>
                        <tbody id="search_content">

                        </tbody>
                </table>
                    <hr>

                    <div align="right">
                        <ul class="pagination pagination-lg">
                        <li id="index">
                      
                        </li>
                        </ul>
                    </div>
                </div>
{% endblock context %}
{% block js %}
<script>
    var pageNo = 1;

    function initTable(index){
        var from_time = $("#from").val();
        var to_time = $("#to").val();
        $.ajax({
            type:"post",
            url:"/home/manage/uid={{ request.session.user_id }}/page="+index,
            data:{"from":from_time, "to":to_time, "pindex":index},
            dataType:"json",
            success: function(data){
                var html = "";
                data = JSON.parse(data);

                for(var i=0; i<data.page_index_num; i++){

                    var picture = data.page[i];
                    var url = picture['purl'];
                    var link_id = picture['id'];
                    var index = i+1;
                    //console.log(typeof(picture.pcreatetime.year));
                    var year = String(picture.pcreatetime.year);
                    var month = "0"+String(picture.pcreatetime.month);
                    var day = "0"+String(picture.pcreatetime.day);
                    var hour = "0"+String(picture.pcreatetime.hour);
                    var minute = "0"+String(picture.pcreatetime.minute);

                    var time = year+'-'+month.slice(-2)+'-'+day.slice(-2)+" "+hour.slice(-2)+":"+minute.slice(-2);

                    html += '<tr align="center" valign="middle" id="tr_'+picture.id+'">';
                    html += '<td>'+String((data.pindex-1)*10+index)+'</td>';
                    html += '<td>'+time+'</td>';
                    html += '<td>'+'<img src="'+url+'">'+'</td>';
                    html += '<td>'+picture['pretime']+'</td>';
                    html += '<td class="operation">'+'<button type="button" class="btn btn-danger" name="delete" id=picture_'+picture.id+'>Delete</button>'
                            +'<a href="/home/detail/pid='+link_id+'" class="btn btn-link" name="detail" id="detail">For More Details</a></td></tr>';
                }
                $("#search_content").html(html);

                html1 = "";
                for(var j=0; j<data.page_num; j++){
                    html1 += '<a href="#" class="indexes" id="'+String(j+1)+'">'+String(j+1)+'</a>'
                }
                $("#index").html(html1);
            }
        })
    }

    function delete_picture(id, index){
        $.ajax({
            type:"post",
            url:"/manage/delete_picture/",
            data:{"id":id},
            dataType:"json",
            success: function(data){
                <!--var html = "";-->
                data = JSON.parse(data)
                if(data.isDelete == '1'){
                    tr_id = 'tr_'+id;
                    console.log(tr_id);
                    $("#"+tr_id).remove();
                    initTable(index);
                }
            }
        })
    }

    $(function () {
        //调用函数,初始化表格
        initTable(pageNo);

        //当点击查询按钮的时候执行
        $("#search").bind("click", function(){
            initTable(pageNo);

        });

        //分页执行
        $("#index").on("click", ".indexes", function(){
            var index = $(this).attr("id");
            alert(index);
            pageNo = index;
            initTable(pageNo);
        })

        //delete button btn-danger
        $("#search_content").on("click", "td>.btn-danger", function(){
            if(confirm("Sure to delete this picture ?")){
                var id = $(this).attr("id").split("_")[1];
                delete_picture(id, pageNo);
            }


        })
    });
</script>
{% endblock js %}

效果:


可以配合ajax实现基本的分页

感谢:前端界面的设计还是不太会,这里感谢几位同学朋友的指导:阮佩昆、赵亮、刘炎彬!另,其实比较想知道工程中是如何实现ajax分页的,望知道的朋友留言告知。

相关文章

网友评论

    本文标题:自制paginator.py

    本文链接:https://www.haomeiwen.com/subject/lgyzyqtx.html