最近在做Django時自己寫了一個Paginator來配合Ajax動態(tài)獲取數(shù)據(jù)。
1辞居、paginator.py
# coding=utf-8
import json
import datetime
from django.forms.models import model_to_dict
class Paginator:
# obj_list:傳入的對象列表; count:每一頁記錄的條數(shù)
def __init__(self, obj_list, count, index):
self.obj_list = obj_list
self.count = count
self.index = index
# 計算總頁數(shù)
def page_num(self):
length = len(self.obj_list)
if length % self.count != 0:
return length // self.count + 1
else:
return length / self.count
# 計算當(dāng)前索引頁記錄條數(shù)
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
# 返回當(dāng)前頁記錄的json集合
def page(self):
json_list = []
day = datetime.datetime.now()
page_index_num = self.page_index_num()
# 循環(huán)當(dāng)前頁
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類型無法直接轉(zhuǎn)化楷怒,這里沒有用到此屬性,故刪除瓦灶,如有需要參照下面的方法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為空刃泡,則用當(dāng)前時間
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 <input class="form-control mr-sm-2" type="datetime-local" name="from" id="from" value="">
To <input class="form-control mr-sm-2" type="datetime-local" name="to" id="to" value="">
<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 () {
//調(diào)用函數(shù)预厌,初始化表格
initTable(pageNo);
//當(dāng)點擊查詢按鈕的時候執(zhí)行
$("#search").bind("click", function(){
initTable(pageNo);
});
//分頁執(zhí)行
$("#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實現(xiàn)基本的分頁
感謝:前端界面的設(shè)計還是不太會曼玩,這里感謝幾位同學(xué)朋友的指導(dǎo):阮佩昆、趙亮败匹、劉炎彬撮胧!另桨踪,其實比較想知道工程中是如何實現(xiàn)ajax分頁的,望知道的朋友留言告知芹啥。