Просто пример реализации пагинации в Django.
В urls.py настраиваем маршрут.
1 2 3 4 5 |
urlpatterns = [ ... path('projects/', views.project_list, name='projects'), ... ] |
В файле views.py создаем метод project_list.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def project_list(request): queryset = Project.objects.all().order_by('-id') paginator = Paginator(queryset, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) data = { 'title': 'Project', 'paginator': paginator, 'page_number': page_number, 'page_obj': page_obj, } return render(request, 'project_list.html', data) |
В папке templates создаем шаблон списка project_list.html и шаблон пагинации pagination.html
project_list.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
{% extends "base.html" %} {% block content %} <div class="container pb-5"> <div class="mb-4 d-flex justify-content-between align-items-center"> <h4 class="mb-4"> Projects </h4> <a href="/project/new/" class="btn btn-outline-success"> Add New </a> </div> <table class="table"> <thead class="bg-secondary"> <tr> <th scope="col">Server</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for project in page_obj %} <tr> <td class="align-middle">{{ project.name }}</td> <td class="align-middle"> <a href="/project/{{ project.id }}/" class="btn btn-outline-success"> Actions </a> <a href="/project/edit/{{ project.id }}/" class="btn btn-outline-success"> Edit </a> </td> </tr> {% endfor %} </tbody> </table> {% include "pagination.html" %} </div> {% endblock %} |
pagination.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{% if page_obj.has_previous or page_obj.has_next %} <nav class="mt-4"> <ul class="pagination"> <li class="page-item mr-1"> <a class="btn btn-outline-success" href="?page=1">First</a> </li> {% if page_obj.has_previous %} <li class="page-item mr-1"> <a class="btn btn-outline-success" href="?page={{ page_obj.previous_page_number }}">Previous</a> </li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if i == page_obj.number %} <li class="page-item mr-1"> <a class="btn btn-success" href="?page={{ i }}">{{ i }}</a> </li> {% elif i > page_obj.number|add:'-4' and i < page_obj.number|add:'4' %} <li class="page-item mr-1"> <a class="btn btn-outline-success" href="?page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item mr-1"> <a class="btn btn-outline-success" href="?page={{ page_obj.next_page_number }}">Next</a> </li> {% endif %} <li class="page-item mr-1"> <a class="btn btn-outline-success" href="?page={{ page_obj.paginator.num_pages }}">Last</a> </li> </ul> </nav> {% endif %} |