首页 > 解决方案 > 分页在 Django 模板页面中不起作用

问题描述

我试图在模板页面中包含分页。但是在执行项目时遇到了模板语法错误。

它说: 无法解析剩余部分:'==i' from 'posts.number==i'

我对此感到非常沮丧。

视图.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)

帖子.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>

标签: pythondjangodjango-viewsdjango-templatesdjango-pagination

解决方案


posts.number请在和之间添加空格i。我建议这样的事情: {%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>

推荐阅读