def aliyun_dashboard(request, page=1): if request.method == 'GET': nodes = CmdbNode.objects.all().order_by('-node__creationTime') paginator = Paginator(nodes, 10) try: records = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. records = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. records = paginator.page(paginator.num_pages) index = records.number max_index = paginator.num_pages if max_index <= 10: page_range = range(1, max_index + 1) elif max_index - index >= 10: page_range = range(index, index + 10) else: start_index = index - (10 - (max_index - index)) + 1 page_range = range(start_index, max_index + 1) if request.method == 'GET': return render(request, 'cmdb/dashboard.html', {'form': AliyunDashboard(), 'records': records, 'page_range': page_range})
前端展示
<nav aria-label="Page navigation"> <ul class="pagination"> {% if records.has_previous %} <li> <a href="{% url 'aliyun_dashboard' records.previous_page_number %}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% endif %} {% if page_range|length > 1 %} {% for pg in page_range %} {% if records.number == pg %} <li class="active"><a href="{% url 'aliyun_dashboard' pg %}">{{ pg }}</a></li> {% else %} <li><a href="{% url 'aliyun_dashboard' pg %}">{{ pg }}</a></li> {% endif %} {% endfor %} {% endif %} {% if records.has_next %} <li> <a href="{% url 'aliyun_dashboard' records.next_page_number %}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> {% endif %} </ul> </nav>