自定义DJango分页类实现,自定义django分页,感觉DJango的分页浏


感觉DJango的分页浏览不是很好用,需要先查出来再搞分页。

由于很常用,所以我自己写了个函数mypaginate(注意我的分页格式很固定,用”&page=2″这种方式)

在view中这样调用:

PAGE_SIZE = 10 #每页十个params = "&keywords=%s&code_lang=%s" % (keywords, lang) #页面链接时候的额外参数offset, page_navi, page_ex = mypaginate(request, total, PAGE_SIZE, params)

然后由render传给模板,模板中这么写:

{% if page_ex.prev %}<a href="{{page_ex.first}}">第一页</a><a href="{{page_ex.prev}}">上一页</a>{% else %}第一页 上一页{% endif %}{% for p, l in page_navi %}<a id="p_{{p}}" href="/code/all/{{l}}">{{p}}</a>{% endfor %}{% if page_ex.max_page %}... <a href="{{page_ex.last}}">{{page_ex.max_page}}</a>{% endif %}{% if page_ex.next %}<a href="{{page_ex.next}}">下一页</a><a href="{{page_ex.last}}">最后页</a>{% else %}下一页 最后页{% endif %}
def mypaginate(request, total, pagesize, params=""):    #get page info    curr = int(request.GET.get('page', 1))    #calculate the offset    offset = (curr – 1) * pagesize    if offset >= total:        offset = total – 1    if offset < 0:        offset = 0    #paginatize    page_navi = []    page_ex = {}    max_page = (total – 1) / pagesize + 1    start = curr – ((curr – 1) % 10)    end = start + 10    if end > max_page + 1:        end = max_page + 1 #remember it's [start, end)    elif max_page > end:        page_ex['max_page'] = max_page    for i in range(start, end):        link = ("?page=%d&" % i) + params        page_navi.append((i, link))    if curr > 1:        page_ex['first'] = ("?page=%d&" % 1) + params        page_ex['prev'] = ("?page=%d&" % (curr – 1)) + params    if curr < max_page:        page_ex['next'] = ("?page=%d&" % (curr + 1)) + params        page_ex['last'] = ("?page=%d&" % max_page) + params

评论关闭