【发布时间】:2021-06-02 17:37:11
【问题描述】:
试图在视图中使用分页器。从 page = request.GET.get('page') 获取任何内容。照原样,对 paginator 的调用会正确限制页面上的帖子,但此后对页面序列的任何调用都会失败。页面将显示,但不会显示任何表单 pagination.html。为清楚起见,Base.html 是所有其他人继承的基本模板。 list.html 是我希望看到 pagination.html 显示的页面。
此代码基于 django 手册。是否需要设置其他东西来为请求查询字典提供“页面”键或更好的分页方式?
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def post_list(request):
object_list = Post.published.all() #a list of the posts
paginator = Paginator(object_list, 4) # 4 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,'blog/post/list.html',{'page': page,'posts': posts})
分页.html
<div class="pagination">
<span class="step-links">
{% if page.has_previous %}
<a href="?page={{ page.previous_page_number }}">Previous</a>
{% endif %}
<span class="current">
Page {{ page.number }} of {{ page.paginator.num_pages }}.
</span>
{% if page.has_next %}
<a href="?page={{ page.next_page_number }}">Next</a>
{% endif %}
</span>
</div>
base.html
#...
<div id="content">
{% block content %}
{% include "pagination.html" with page=posts %}
{% endblock %}
</div>
#...
list.html
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
<h1>My Blog</h1>
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
{% endblock %}
【问题讨论】:
-
您是否会在
blog/post/list.html中填写名为 content 的块? -
我相信我做到了。我已经用 list.html 更新了帖子,它扩展了 base.html,我相信这是 {%block content %} 的填充
标签: python-3.x django web django-views