Browse Source

Постраничная навигация.

Количество записей на страницу устанавливается в settings.py `ITEMS_PER_PAGE`
master
Дмитрий 3 years ago
parent
commit
f95e2276fd
  1. 4
      blog/blog/settings.py
  2. 72
      blog/posts/templates/posts/index.html
  3. 1
      blog/posts/urls.py
  4. 23
      blog/posts/views.py

4
blog/blog/settings.py

@ -157,3 +157,7 @@ STATICFILES_DIRS = [
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Количество элементов для страницы.
# Используется в постраничной навигации.
ITEMS_PER_PAGE: int = 10

72
blog/posts/templates/posts/index.html

@ -20,6 +20,76 @@
{% endfor %} {% endfor %}
{% endif %} {% endif %}
</div> </div>
<section> </section>
<!-- Pagination -->
{% comment %}
Обработка пагинации построена на проверке условий: первые страницы,
последние страницы, страницы в середине большого кол-ва страниц, малое
количество страниц. Для каждого случая - свой код. Также требуются
перменные: current_page (текущая страница) и объект paginator.
{% endcomment %}
<section class="section">
<nav class="pagination is-centered" role="navigation" aria-label="pagination">
{% if paginator.num_pages <= 5 %}
<ul class="pagination-list">
{% for pnum in paginator.page_range %}
{% if pnum == current_page %}
<li><a class="pagination-link is-current" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{pnum}}</a></li>
{% else %}
<li><a class="pagination-link" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{pnum}}</a></li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
{% if paginator.num_pages > 5 %}
<ul class="pagination-list">
{# навигация в середине диапазона страниц, когда есть центральные, а до краев еще далеко #}
{% if current_page > 3 and current_page < paginator.num_pages|add:-3 %}
<li><a class="pagination-link" aria-label="На страницу 1" href={% url 'posts:page' 1 %}>1</a></li>
<li><span class="pagination-ellipsis">&hellip;</span></li>
<li><a class="pagination-link" aria-label="На страницу {{ current_page|add:-1 }}" aria-current="page" href={% url 'posts:page' current_page|add:-1 %}>{{ current_page|add:-1 }}</a></li>
<li><a class="pagination-link is-current" aria-label="На страницу {{current_page}}" aria-current="page" href={% url 'posts:page' current_page %}>{{ current_page }}</a></li>
<li><a class="pagination-link" aria-label="На страницу {{ current_page|add:1 }}" aria-current="page" href={% url 'posts:page' current_page|add:1 %}>{{ current_page|add:1 }}</a></li>
<li><span class="pagination-ellipsis">&hellip;</span></li>
<li><a class="pagination-link" aria-label="На страницу {{ paginator.num_pages }}">{{ paginator.num_pages }}</a></li>
{# навигация на первых страницах (левый граничный случай) #}
{% elif current_page <= 3 and current_page <= paginator.num_pages %}
{% for pnum in paginator.page_range|slice:":5" %}
{% if pnum == current_page %}
<li><a class="pagination-link is-current" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{ pnum }}</a></li>
{% else %}
<li><a class="pagination-link" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{ pnum }}</a></li>
{% endif %}
{% endfor %}
<li><span class="pagination-ellipsis">&hellip;</span></li>
<li><a class="pagination-link" aria-label="На страницу {{paginator.num_pages}}" href={% url 'posts:page' paginator.num_pages %}>{{paginator.num_pages}}</a></li>
{# навигация на последних страницах (правый граничный случай) #}
{% elif current_page > 2 and current_page <= paginator.num_pages %}
<li><a class="pagination-link" aria-label="На страницу 1" href={% url 'posts:page' 1 %}>1</a></li>
<li><span class="pagination-ellipsis">&hellip;</span></li>
{% for pnum in paginator.page_range|slice:"-5:" %}
{% if pnum == current_page %}
<li><a class="pagination-link is-current" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{ pnum }}</a></li>
{% else %}
<li><a class="pagination-link" aria-label="На страницу {{pnum}}" aria-current="page" href={% url 'posts:page' pnum %}>{{ pnum }}</a></li>
{% endif %}
{% endfor %}
{% endif %}
</ul>
{% endif %}
</nav>
</section>
{% endautoescape %} {% endautoescape %}
{% endblock %} {% endblock %}

1
blog/posts/urls.py

@ -5,4 +5,5 @@ app_name = "posts"
urlpatterns = [ urlpatterns = [
path("", views.index, name="index"), path("", views.index, name="index"),
path("<int:post_id>/", views.detail, name="detail"), path("<int:post_id>/", views.detail, name="detail"),
path("page/<int:page>", views.index, name="page"),
] ]

23
blog/posts/views.py

@ -3,6 +3,8 @@ from django.http import HttpResponse
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from .models import Post from .models import Post
from comments.models import Comment from comments.models import Comment
from django.core.paginator import Paginator
from blog.settings import ITEMS_PER_PAGE
from comments import services as comments_services from comments import services as comments_services
@ -10,10 +12,25 @@ import re
from re import Match from re import Match
def index(request): def index(request, page: int = 1):
"""Список постов.""" """Список постов."""
post_list = Post.objects.order_by("-pub_date")[:20]
return render(request, "posts/index.html", {"posts": post_list}) post_list = Post.objects.order_by("-pub_date")[:ITEMS_PER_PAGE]
paginator = Paginator(Post.objects.order_by("-pub_date"), ITEMS_PER_PAGE)
if page > paginator.num_pages:
page = paginator.num_pages
if page < 1:
page = 1
posts = paginator.get_page(page)
return render(
request,
"posts/index.html",
{"posts": posts, "paginator": paginator, "current_page": page},
)
def image_processing(match: Match, images: QuerySet) -> str: def image_processing(match: Match, images: QuerySet) -> str:

Loading…
Cancel
Save