您可以按照以下方式修改代码,以只显示五个页码并在点击时显示全部页码:
def index(request, pIndex=1):
'''浏览信息'''
nmod = Orders.objects
nlist = nmod.filter(status__lt=9)
mywhere = []
# 获取并判断搜索条件
kw = request.GET.get("keyword", None)
if kw:
nlist = nlist.filter(Q(username__contains=kw) | Q(nickname__contains=kw))
mywhere.append('keyword=' + kw)
# 获取、判断并封装状态status搜索条件
status = request.GET.get('status', '')
if status != '':
nlist = nlist.filter(status=status)
mywhere.append("status=" + status)
nlist = nlist.order_by("id") # 对id排序
# 执行分页处理
pIndex = int(pIndex)
page = Paginator(nlist, 10) # 以每页5条数据分页
maxpages = page.num_pages # 获取最大页数
# 判断当前页是否越界
if pIndex > maxpages:
pIndex = maxpages
if pIndex < 1:
pIndex = 1
# 获取当前页数据和页码列表信息
list2 = page.page(pIndex)
plist = page.page_range
# 只显示五个页码,其他的隐藏,点击时显示全部页码
if maxpages <= 5:
visible_pages = plist
else:
start_page = max(1, pIndex - 2)
end_page = min(maxpages, start_page + 4)
if start_page == 1:
visible_pages = range(start_page, end_page+1)
elif end_page == maxpages:
visible_pages = range(end_page-4, end_page+1)
else:
visible_pages = range(start_page-1, end_page+2)
context = {"orderlist": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages,
'mywhere': mywhere, 'visible_pages': visible_pages}
return render(request, "myadmin/order/index.html", context)
在模板文件中,您可以使用 {% for page_num in plist %} 循环来渲染页码链接,然后根据需要显示隐藏的页码。例如:
<div class="pagination">
{% for page_num in plist %}
{% if page_num in visible_pages %}
<a href="?pIndex={{ page_num }}">{{ page_num }}</a>
{% else %}
<!-- 点击时显示全部页码 -->
<a href="?pIndex={{ page_num }}">...</a>
{% endif %}
{% endfor %}
</div>
这样修改后,只会显示五个页码链接,并在不足五个页码时全部显示。当点击省略号链接时,会展示出所有的页码。
内容由零声教学AI助手提供,问题来源于学员提问




