Django5 自定义分页器

views

def public_main(request, cid=0, page=1):
    categories = Category.objects.all()
    # 检索分类
    if cid == 0:
        cid = categories.first().cid  # 第一个分类的cid
    page_now = page

    kw = request.GET.get("kw")
    # 文章检索
    if kw == None:
        articles = Article.objects.filter(cid=cid)
    else:
        articles = Article.objects.filter(cid=cid, title__contains=kw)

    # 产生分页器
    paginator = SelfPaginator(articles, 2)
    # 分页对象
    # page表示当前页
    pager = paginator.page(page)
    pager.page_range = paginator.custom_range(paginator.num_pages,page, 3)

    return render(request, "wenzhang_xinwen.html", locals())

tools

import math
from django.core.paginator import Paginator

class SelfPaginator(Paginator):
    def custom_range(self, num_pages, page, per_range):
        self.num_pages = num_pages
        # 页码数大于总页数
        if per_range > self.num_pages:
            return range(1, self.num_pages + 1)
        elif page <= per_range // 2:
            return range(1, per_range + 1)
        elif page + per_range // 2 > self.num_pages:
            return range(self.num_pages - per_range + 1, self.num_pages + 1)
        else:
            return range(page - per_range // 2, page + math.ceil(per_range / 2))

page.html

<div class="pageSelect">
	<span><b>{{ paginator.count }}</b> 条 每页 <b>{{ paginator.per_page }}</b>条   {{ page_now }}/{{ paginator.num_pages }}</span>
	<div class="pageWrap">
		{% if page > 1 %}
		<a href="{% url 'App:main' cid=cid page=page_now|add:'-1' %}" class="pagePre"><i class="ico-pre">&nbsp;</i></a>
		{% endif %}
		    {% for page in pager.page_range %}
				{% if page == page_now %}
					<a href="{% url 'App:main' cid=cid page=page %}" class="pagenumb cur">{{ page }}</a>
				{% else %}
					<a href="{% url 'App:main' cid=cid page=page %}" class="pagenumb">{{ page }}</a>
				{% endif %}
			{% endfor %}
		{% if page < paginator.num_pages %}
		<a href="{% url 'App:main' cid=cid page=page_now|add:'1' %}" class="pagenext"><i class="ico-next">&nbsp;</i></a>
		{% endif %}
	</div>
</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值