在记录上添加django分页器

时间:2018-11-27 09:39:51

标签: python django paginator

这是我的记录应用程序views.py,我想在记录列表的结果上添加分页,该列表由以下代码生成,并且还提供模板的解决方案。 请帮我。 谢谢。

from django.shortcuts import render
from purchase_report.views import *
import datetime
from datetime import datetime
from purchase_report.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def display_records(request):
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    purchase_date = PurchaseReport.objects.filter(purchase_date__range=[start_date, end_date])

    return render(request, 'records.html', {'purchase_date': purchase_date,
                                        'start_date': start_date,
                                        'end_date': end_date})

1 个答案:

答案 0 :(得分:0)

from django.shortcuts import render
from purchase_report.views import *
import datetime
from datetime import datetime
from purchase_report.models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def display_records(request):
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    purchase_date = PurchaseReport.objects.filter(purchase_date__range=[start_date, end_date])
    paginator = Paginator(purchase_date, 25) # Show 25 purchase_date per page

    page = request.GET.get('page')
    purchase_date = paginator.get_page(page)

    return render(request, 'records.html', {'purchase_date': purchase_date,
                                        'start_date': start_date,
                                        'end_date': end_date})

然后在您的模板中,您可以像通常那样对它们进行迭代

{% for date in purchase_date %}
    {{ date.<your_model attribute here> }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if purchase_date.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ purchase_date.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ purchase_date.number }} of {{ purchase_date.paginator.num_pages }}.
        </span>

        {% if purchase_date.has_next %}
            <a href="?page={{ purchase_date.next_page_number }}">next</a>
            <a href="?page={{ purchase_date.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>

您需要按自己喜欢的方式来设置样式/自定义此分页链接,但是如果您仍不太清楚它,就无法实现您的分页想法。选中https://docs.djangoproject.com/en/2.1/topics/pagination/