項目開發中使用django_tables2展示數據之切換每頁顯示數的另類實現方法

在使用python+django開發web版《IT資產管理系統》過程中,使用了django_tables2展示數據,爲了實現切換每頁顯示10行,25行,50行這個功能,需要前端向後端的視圖函數傳遞per_page參數,通用的實現方法是在現有的url後面加上&per_page=XX就可以了,這需要用到request.get_full_path, 因爲在測試時遇到了難題,未能實現我要的功能,本來 django_tables2會自動識別url傳遞過來的參數,並按收到XX這個數調整每頁顯示記錄的數量,按理說是最簡單的實現方法。

本人嘗試了另外一種實現方法,這忽略考慮系統性能,只爲實現所需的功能。以下是截圖:可以看到在清單的下方,添加了三個切換的鏈接,

1

 

這三個鏈接代碼如下:

<div class="col-md-2"> 共有: {{ table.paginator.count }}條記錄,分{{ table.paginator.num_pages }}頁顯示,</div>  <nav><ul>當前:{{ table.paginator.per_page }}行/頁,切換: <a href="changeperpage?ppage=10">[10行/頁] </a> - <a href="changeperpage?ppage=25" >[25行/頁] </a>- <a href="changeperpage?ppage=50" >[50行/頁] </a></ul></nav>

鏈接到後端的視圖函數changeperpage(),代碼如下:

def changeperpage(request):
    next = request.session.get('current_path','displaypc2')

    request.session['per_page']=request.GET.get('ppage','25')

    return HttpResponseRedirect(next)

 

此視圖函數負責接受url後面的ppage變量,並修改session變量per_page, 然後跳轉到next,這個next是前端資產列表的當前url。

對應的視圖函數diaplaypc2:

def displaypc2(request):
    full_path=request.get_full_path()
    
    request.session['current_path']=full_path
    
    f = pclistFilter(request.GET)
    siteid = request.session.get('current_site')
    table=f.qs.filter(site_list_id=siteid,motable__hosttype_list_id__in=(1,2,3,12),pcstatustable_id__in=(1,2,3,5))

    #totalrow=table.count()
    #django_tables2.paginators.Paginator.
    table = pctable2(table)

    per_page=request.session.get('per_page',10)
    RequestConfig(request, paginate={"per_page":per_page}).configure(table)
    return render(request,'displaypc.html',{'table':table,'m':'dm','filter':f})

 

這樣就可以自由切換每頁顯示記錄數了。而且可以保持查詢結果的前提下切換每頁顯示記錄數。

查詢資產類型爲laptop, 以下是10行/頁

2

以下是在上一頁顯示的查詢結果的基礎上,從10行/頁切換爲25行/頁,點相應的鏈接【25行/頁】,結果顯示如下:

3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章