【发布时间】:2020-12-16 15:37:28
【问题描述】:
https://docs.djangoproject.com/en/3.0/topics/pagination/
我引用此 URL 是为了向我的应用程序添加分页,但我无法获得干净的 URL。 我得到的网址:localhost:8000/?page=2 我要的网址:localhost:8000/page/2
index.html
<div class="row">
<div class="col-md-12">
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
{% if queryset.has_next %}
<li class="page-item">
<a class="page-link" href="?{{ page_request_var }}={{ queryset.next_page_number }}">Next</a>
</li>
{% endif %}
</ul>
</nav>
</div><!-- end col -->
</div><!-- end row -->
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('page/<int:pageno>/', views.index, name='index'), #This path was added just for testing purpose. so that I can hit the URL: website.com/page/3
]
views.py
def index(request, pageno=1):
post_list = Post.objects.filter(featured=True)
paginator = Paginator(post_list, 2)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginted_query = paginator.page(page)
except PageNotAnInteger:
paginted_query = paginator.page(1)
except EmptyPage:
paginted_query = paginator.page(paginator.num_pages)
context = {
'queryset':paginted_query,
'page_request_var':page_request_var
}
return render(request, 'index.html', context)
通过这样做,我可以访问干净的 URL,但分页不起作用。它一直在第 2 页上向我显示相同的登录页面,并且没有进一步分页。
【问题讨论】:
-
请问您能分享您的查看代码吗?您需要确保您使用的是从 URL 传入的页码。
标签: python django django-views pagination