分页在 Django 模板页面中不起作用
pagination does not work in Django template page
我试图在模板页面中包含分页。但是在执行项目的时候遇到模板语法错误
它说:
无法解析余数:来自 'posts.number==i'
的“==i”
对此我感到非常沮丧。
views.py
def posts(request):
posts = Post.objects.filter(active=True)
myFilter = PostFilter(request.GET, queryset=posts)
posts = myFilter.qs
page = request.GET.get('page')
paginator = Paginator(posts, 3)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {'posts': posts, 'myFilter': myFilter}
return render(request, 'base/posts.html', context)
posts.html
<div class="row">
{%if posts.has_other_pages%}
<ul class="pagination">
{%for i in posts.paginator.page_range%}
{%if posts.number==i%}
<li class="page-item"><a class="active page-link">{{i}}</a></li>
{%else%}
<li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li>
{%endif%}
{%endfor%}
</ul>
{%endif%}
</div>
请在posts.number
和i
之间加上space。我建议这样的事情:
{%if posts.number == i%}
而不是 {%if posts.number==i%}
<div class="row">
{%if posts.has_other_pages%}
<ul class="pagination">
{%for i in posts.paginator.page_range%}
{%if posts.number == i%}
<li class="page-item"><a class="active page-link">{{i}}</a></li>
{%else%}
<li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li>
{%endif%}
{%endfor%}
</ul>
{%endif%}
</div>
我试图在模板页面中包含分页。但是在执行项目的时候遇到模板语法错误
它说: 无法解析余数:来自 'posts.number==i'
的“==i”对此我感到非常沮丧。
views.py
def posts(request):
posts = Post.objects.filter(active=True)
myFilter = PostFilter(request.GET, queryset=posts)
posts = myFilter.qs
page = request.GET.get('page')
paginator = Paginator(posts, 3)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {'posts': posts, 'myFilter': myFilter}
return render(request, 'base/posts.html', context)
posts.html
<div class="row">
{%if posts.has_other_pages%}
<ul class="pagination">
{%for i in posts.paginator.page_range%}
{%if posts.number==i%}
<li class="page-item"><a class="active page-link">{{i}}</a></li>
{%else%}
<li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li>
{%endif%}
{%endfor%}
</ul>
{%endif%}
</div>
请在posts.number
和i
之间加上space。我建议这样的事情:
{%if posts.number == i%}
而不是 {%if posts.number==i%}
<div class="row">
{%if posts.has_other_pages%}
<ul class="pagination">
{%for i in posts.paginator.page_range%}
{%if posts.number == i%}
<li class="page-item"><a class="active page-link">{{i}}</a></li>
{%else%}
<li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li>
{%endif%}
{%endfor%}
</ul>
{%endif%}
</div>