我目前正在处理我的Django分页问题。我有一个9个对象的查询集,并将一个对象分页到一个页面。所以我应该总共有9页。
Paginator显示我有9页,但是当我点击“下一页”页面按钮时我的(总是在最后/最后两页)我的网址转到:http://127.0.0.1:8000/forum/1?page=7
然后我得到404页面未找到错误以及“无效页面(7):该页面不包含任何结果”
这是我的班级代码:
class DirectoryClass(generic.ListView):
template_name = "forum_directory.html"
model = Directory
paginate_by = 1
def get_context_data(self, **kwargs):
context = super(DirectoryClass, self).get_context_data(**kwargs)
directory = Directory.objects.filter(pk=self.kwargs['directory_id'])
context['page'] = 'forum'
context['name'] = directory.first().name
context['user'] = self.request.user
topic_set = directory.first().topic_set.all().order_by('-last_post')
print(topic_set.all())
paginator = Paginator(topic_set, self.paginate_by)
page = self.request.GET.get('page')
try:
topic_set = paginator.page(page)
except PageNotAnInteger:
topic_set = paginator.page(1)
except EmptyPage:
topic_set = paginator.page(paginator.num_pages)
context['topics'] = topic_set
context['page'] = page
return context
以下是用于更改页面的HTML:
<div style="width: 1240px; margin: auto; text-align: right;">
{% if topics.has_other_pages %}
<ul class="pagination forum-pagination">
{% if topics.has_previous %}
<li><a href="?page={{ topics.previous_page_number }}">«</a></li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in topics.paginator.page_range %}
{% if topics.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li><a href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if topics.has_next %}
<li><a href="?page={{ topics.next_page_number }}">»</a></li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
这是网址
path(r'/<int:directory_id>',views.DirectoryClass.as_view(), name='forum_directory'),
我在这里做错了什么?
答案 0 :(得分:1)
def get_context_data(self, **kwargs):
context = super(DirectoryClass, self).get_context_data(**kwargs)
context['page'] = 'forum'
context['user'] = self.request.user
return context
def get_queryset(self):
directory = Directory.objects.filter(pk=self.kwargs['directory_id'])
topics = directory.first().topic_set.all().order_by('-last_post')
return topics
仅在ListView中使用它,因为Django为所有基于类的视图提供分页