html 为Django切片分页(+ Bootstrap样式)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 为Django切片分页(+ Bootstrap样式)相关的知识,希望对你有一定的参考价值。

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django import template


register = template.Library()


@register.inclusion_tag('_pagination.html', takes_context=True)
def get_pagination(context, first_last_amount=2, before_after_amount=4):
    page_obj = context['page_obj']
    paginator = context['paginator']
    is_paginated = context['is_paginated']
    page_numbers = []

    # Pages before current page
    if page_obj.number > first_last_amount + before_after_amount:
        for i in range(1, first_last_amount + 1):
            page_numbers.append(i)

        if first_last_amount + before_after_amount + 1 != paginator.num_pages:
            page_numbers.append(None)

        for i in range(page_obj.number - before_after_amount, page_obj.number):
            page_numbers.append(i)

    else:
        for i in range(1, page_obj.number):
            page_numbers.append(i)

    # Current page and pages after current page
    if page_obj.number + first_last_amount + before_after_amount < paginator.num_pages:
        for i in range(page_obj.number, page_obj.number + before_after_amount + 1):
            page_numbers.append(i)

        page_numbers.append(None)

        for i in range(paginator.num_pages - first_last_amount + 1, paginator.num_pages + 1):
            page_numbers.append(i)

    else:
        for i in range(page_obj.number, paginator.num_pages + 1):
            page_numbers.append(i)

    return {
        'paginator': paginator,
        'page_obj': page_obj,
        'page_numbers': page_numbers,
        'is_paginated': is_paginated,
    }
{% load paginator_tags %}

<!-- ... -->

{% get_pagination 2 1 %}
{% if is_paginated %}
<div class="pagination-wrapper">
    <ul class="pager">
    {% if page_obj.has_previous %}
        <li><a href="?page={{ page_obj.previous_page_number }}">Anterior</a></li>
    {% endif %}
    {% for page in page_numbers %}
        {% if page %}
            {% ifequal page page_obj.number %}
                <li class="disabled"><a href="#">{{ page }}</a></li>
            {% else %}
                <li><a href="?page={{ page }}">{{ page }}</a></li>
            {% endifequal %}
        {% else %}
            ...
        {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
        <li><a href="?page={{ page_obj.next_page_number }}">Siguiente</a></li>
    {% endif %}
    </ul>
</div>
{% endif %}

以上是关于html 为Django切片分页(+ Bootstrap样式)的主要内容,如果未能解决你的问题,请参考以下文章

django 分页与美化

Python Day71 django分页及session介绍

精确查找的QuerySet值必须使用Django中的切片错误限制为一个结果

python之路_day71_django分页及session介绍

Django实现自定义分页

如何在 django 中为上下文对象执行分页?