首页 > 代码库 > django 自定义分页模块

django 自定义分页模块

django 自定义分页模块

from django.shortcuts import render, HttpResponse, redirect
from django.utils.safestring import mark_safe

class Page(object):
    def __init__(self, current_page):
        self.current_page = int(current_page)

    @property
    def start(self):
        return (self.current_page - 1)*10

    @property
    def end(self):
        return self.current_page * 10

    def page_str(self, all_item, base_url):
        all_page, div = divmod(all_item, 10)
        if div > 0:
            all_page += 1

        page_list = []

        if all_page <= 11:
            start = 1
            end = 11
        else:
            if self.current_page <= 6:
                start = 1
                end = 11 + 1
            else:
                start = self.current_page - 5
                end = self.current_page + 6
                if self.current_page + 6 > all_page:
                    start = all_page - 10
                    end = all_page + 1
        for i in range(start, end):
            if i == self.current_page:
                temp = <a style="color:red;font-size:26px;padding: 5px" href="http://www.mamicode.com/%s?page=%d">%d</a> % (base_url, i, i)
            else:
                temp = <a style="padding: 5px" href="http://www.mamicode.com/%s?page=%d">%d</a> % (base_url, i, i)
            page_list.append(temp)

        if self.current_page > 1:
            pre_page = <a href="http://www.mamicode.com/%s?page=%d">上一页</a> % (base_url, self.current_page - 1)
        else:
            pre_page = <a href="javascript:void(0);">上一页</a>

        # 下一页
        if self.current_page >= all_page:
            next_page = <a href="javascript:void(0);">下一页</a>
        else:
            next_page = <a href="http://www.mamicode.com/%s?page=%d">下一页</a> % (base_url, self.current_page + 1)

        page_list.insert(0, pre_page)
        page_list.append(next_page)
        return mark_safe("".join(page_list))


def user_list(request):
    current_page = request.GET.get(page, 1)
    page_obj = Page(current_page)
    # 把方法改造成属性(2),这样在下面调用方法的时候就不需要加括号了
    result = models.UserInfo.objects.all()[page_obj.start:page_obj.end]
    all_item = models.UserInfo.objects.all().count()
    page_str = page_obj.page_str(all_item, /user_list/)
    return render(request, user_list.html, {"result": result, page_str: page_str})

 html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <table>
        {% for line in result %}
            <tr>
                <td>{{ line.user }}</td>
                <td>{{ line.password }}</td>
                <td>{{ line.gender }}</td>
            </tr>
        {% endfor %}
    </table>

    <div>
        {{ page_str }}
    </div>
</body>
</html>

 

django 自定义分页模块